SlideShare ist ein Scribd-Unternehmen logo
1 von 7
Cool modal Popup window with fade effect for mobile web – CSS3
and JavaScript
A post from my Blog: http://jbkflex.wordpress.com/2012/01/30/cool-modal-popup-window-with-fade-
effect-for-mobile-web-css3-and-javascript/

In this tutorial I will talk about creating a very cool modal popup window for iPhone and Android using CSS3 and
Javascript. The modal popup window will display a message with fade-in and fade-out effect. It will also have drop
shadows, rounded corners, gradient background which I will apply using the latest CSS3 techniques. I have a demo
app already created. Click on the Launch PopUp button to open the modal window and then tap outside the modal
window to close it.
Link to demo: http://jbk404.site50.net/css3/modalwindow/
The app is meant for mobile web and you can view it in iPhone/iPod or Android or even Blackberry mobile web
browsers. But nevertheless you can check it out on Google Chrome and Safari which are web-kit based browsers, in
your computer.




What is a modal popup window?
A window dialog box with a message that opens up in the browser page on top of every other component in the page.
So it is a popup window. The user cannot interact with the controls in the background until the popup window is
hidden, hence it is a modal window. A transparent dark background usually covers the entire page beneath the popup
window – our modal overlay. You can see it in the demo.
Getting started
I have a basic HTML page setup as you can see in the demo. The HTML code block is below,

<section id="wrapper">

  <header>

     <span>Modal PopUp</span>

  </header>

  <article>

     <input type="button" value="Another button" />

     <br />

     <p>Tap on the Launch PopUp button below to open the modal window. And then tap
outside the window to close it. There is another button above which shows that you
cannot interact with it while the popup is open.

     </p>

     <br />

     <input type="button" id="popUpBtn" value="Launch PopUp" />

  </article>

</section>


Everything is wrapped inside a wrapper element. This is mainly to create a full screen mobile web app. I have already
talked about it in one of my earlier post here. Coming back to the HTML block above, I have a header at the top and
then the content area which has the instruction message and the two buttons. When user taps on theLaunch
PopUp button the modal window shows with a transparent background. For the modal popup window I will create two
things – a modal overlay which will act as the transparent background, and then the popup window with the message.
I will create these two elements dynamically in java script and then append it to the document body.
Creating the modal overlay transparent background
First let us see how to create the transparent background. Let me officially call it modal overlay from now onwards as
I have been using the terms interchangeably quite a lot.
The action starts only when user clicks on the launch button so I do not have the modal overlay element written in the
HTML code block. I will create the overlay element in java script and then append it to the body. To give it a dark
transparent background I will use simple CSS. Also one thing to notice is that the modal overlay occupies the entire
browser page’s dimension. We can achieve this by setting the width and height to 100% in CSS. The overlay is
supposed to appear over all other controls in the page so that user cannot interact with them in the background. Now,
how do I do that? The answer is simple. Once the overlay element is created in java script, we append it to the
document body, so it is at the top of the DOM stack and all other elements come below it. This gives it the modal
behavior. While the overlay is open you cannot interact with the components beneath it. Also you can specify a higher
z-index value in CSS, if you want. Now, let’s check out the java script code and the CSS below,

var overlayElement = document.createElement("div");

overlayElement.className = 'modalOverlay';

document.body.appendChild(overlayElement);


The CSS

.modalOverlay

{

    width:100%;

    height:100%;

    position:absolute;

    top:0;

    left:0;

    margin:0;

    padding:0;

    background:#000;

 opacity:0;

    -webkit-transition: opacity 0.3s ease-in;

    z-index:101;

}


Initially the opacity is set to 0. Later, I will set the opacity to a value higher than zero (but less than 1 so that it is
transparent) in the script. I will talk about this in a moment. Also another CSS3 property –webkit-transition is set to
make the change of opacity smooth. This will give it the fade-in effect.
Creating the popup window and displaying the custom message
Now that our modal overlay is done, let’s see how to deal with the actual pop up window that will display our custom
message.
The concept is similar to that of the overlay window we have just created. I will create it in java script and then
append it to the body. The custom message will be displayed inside the popup window element using
theinnerHTML property. Here is the necessary script,

var modalWindowElement = document.createElement("div");

modalWindowElement.className = 'modalWindow';

modalWindowElement.innerHTML = msg;

modalWindowElement.style.left = (window.innerWidth - 200) / 2 + "px";

document.body.appendChild(modalWindowElement);


The fourth statement modalWindowElement.style.left positions the popup in the center of the page horizontally.
Now, let’s see the CSS for our popup window.

.modalWindow

{

    position:fixed;

    top:150px;

    margin:0;

    border:2px solid #fff;

    width:180px;

    /*height:30px;*/

    text-align:center;

    word-spacing:2px;

    line-height:15px;

    font-weight:bold;

    font-size:13px;

    color:#fff;

    padding:10px;

    opacity:0;
z-index:102;

    background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #7c9bc0),
color-stop(2%, #416086), color-stop(100%, #293e56));

    -webkit-border-radius:8px;

    -webkit-box-shadow:-1px 2px 12px rgba(0, 0, 0, 0.91);

    -webkit-transition: opacity 0.3s ease-in;

}


The last four style rules are meant for background gradient color, rounded corners, and drop shadow and then I have
added a transition to the opacity of the popup to give it a fade effect.
Adding the fade effect
To add the fade-in effect to both the overlay and the popup I set the opacity to a value higher than 0. You can see in
the script below, I have set an opacity of 0.4 to the overlay to make it transparent. The popup window gets opacity of
1 as expected. This change in opacity from earlier values of 0 will trigger the transition that we have set in CSS and
will make the change happen over time and smoothly. This gives it a fade-in effect.

setTimeout(function() {

    modalWindowElement.style.opacity = 1;

    overlayElement.style.opacity = 0.4;

    overlayElement.addEventListener("click", hidePopUpMessage, false);

}, 300);


I have added a timeout value of 300ms so that the change in opacity happens after the elements have been added to
the DOM and rendered properly.
If you are still not clear about fade effects in CSS3, you can go through a dedicated tutorial on it from one of my
earlier post, here.
Creating rounded corners, gradient background, and drop shadow
These can be done very easily now with CSS3. So I will not explain much. You can go through my blog and find out
enough materials on it. These effects give the popup window a realistic look and a 3d effect, as if it is floating over the
browser window.
Hiding the popup window
Now that the popup window is displayed, we also need to hide it. The process is simple and just the reverse of
displaying it. When you tap outside the popup it is hidden. So I have a specific function for it that is called when user
taps on the overlay outside the popup window. Inside the function I set the opacity to 0 again, to give it a fade-out
effect and then remove the elements from the DOM. You can check out the code along with the full script below,

<script type="text/javascript">
var overlayElement = null;

var modalWindowElement = null;

window.addEventListener('load', initApp, false);




function initApp() {

    setTimeout(function() { window.scrollTo(0, 1); }, 10);

    document.getElementById("popUpBtn").addEventListener("click", function() {

      showPopUpMessage("TADAAAA !<p>This is my cool pop up window with rounded corners,
gradient background and drop shadow.</p>");

    }, false);

}

//show the modal overlay and popup window

function showPopUpMessage(msg) {

    overlayElement = document.createElement("div");

    overlayElement.className = 'modalOverlay';

    modalWindowElement = document.createElement("div");

    modalWindowElement.className = 'modalWindow';

    modalWindowElement.innerHTML = msg;

    modalWindowElement.style.left = (window.innerWidth - 200) / 2 + "px";

    document.body.appendChild(overlayElement);

    document.body.appendChild(modalWindowElement);

    setTimeout(function() {

      modalWindowElement.style.opacity = 1;

      overlayElement.style.opacity = 0.4;

      overlayElement.addEventListener("click", hidePopUpMessage, false);
}, 300);

}

//hide the modal overlay and popup window

function hidePopUpMessage() {

    modalWindowElement.style.opacity = 0;

    overlayElement.style.opacity = 0;

    overlayElement.removeEventListener("click", hidePopUpMessage, false);

    setTimeout(function() {

      document.body.removeChild(overlayElement);

      document.body.removeChild(modalWindowElement);

    }, 400);

}

</script>


Conclusion
This was a simple tutorial on creating a very nice popup window displaying a custom message. While the focus was
based on mobile devices such as iPhone, iPod and other smart phones with web-kit browsers, you can certainly use
it for desktop applications as well. The example already runs in Google Chrome and Safari browsers. You can modify
it (mainly the CSS) to run on all other desktop browsers as well. Below is the link to the demo once again, check it out
in your iPhone/iPod/Android or Blackberry browser. For the full code refer the source.
Link: http://jbk404.site50.net/css3/modalwindow/
If you do not have one, check it out in an online iPhone simulator: http://www.iphonetester.com/

Weitere ähnliche Inhalte

Kürzlich hochgeladen

Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 

Kürzlich hochgeladen (20)

Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

Empfohlen

Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 

Empfohlen (20)

Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 

Cool modal Popup window with fade effect for mobile web – CSS3 and JavaScript

  • 1. Cool modal Popup window with fade effect for mobile web – CSS3 and JavaScript A post from my Blog: http://jbkflex.wordpress.com/2012/01/30/cool-modal-popup-window-with-fade- effect-for-mobile-web-css3-and-javascript/ In this tutorial I will talk about creating a very cool modal popup window for iPhone and Android using CSS3 and Javascript. The modal popup window will display a message with fade-in and fade-out effect. It will also have drop shadows, rounded corners, gradient background which I will apply using the latest CSS3 techniques. I have a demo app already created. Click on the Launch PopUp button to open the modal window and then tap outside the modal window to close it. Link to demo: http://jbk404.site50.net/css3/modalwindow/ The app is meant for mobile web and you can view it in iPhone/iPod or Android or even Blackberry mobile web browsers. But nevertheless you can check it out on Google Chrome and Safari which are web-kit based browsers, in your computer. What is a modal popup window? A window dialog box with a message that opens up in the browser page on top of every other component in the page. So it is a popup window. The user cannot interact with the controls in the background until the popup window is
  • 2. hidden, hence it is a modal window. A transparent dark background usually covers the entire page beneath the popup window – our modal overlay. You can see it in the demo. Getting started I have a basic HTML page setup as you can see in the demo. The HTML code block is below, <section id="wrapper"> <header> <span>Modal PopUp</span> </header> <article> <input type="button" value="Another button" /> <br /> <p>Tap on the Launch PopUp button below to open the modal window. And then tap outside the window to close it. There is another button above which shows that you cannot interact with it while the popup is open. </p> <br /> <input type="button" id="popUpBtn" value="Launch PopUp" /> </article> </section> Everything is wrapped inside a wrapper element. This is mainly to create a full screen mobile web app. I have already talked about it in one of my earlier post here. Coming back to the HTML block above, I have a header at the top and then the content area which has the instruction message and the two buttons. When user taps on theLaunch PopUp button the modal window shows with a transparent background. For the modal popup window I will create two things – a modal overlay which will act as the transparent background, and then the popup window with the message. I will create these two elements dynamically in java script and then append it to the document body. Creating the modal overlay transparent background First let us see how to create the transparent background. Let me officially call it modal overlay from now onwards as I have been using the terms interchangeably quite a lot. The action starts only when user clicks on the launch button so I do not have the modal overlay element written in the HTML code block. I will create the overlay element in java script and then append it to the body. To give it a dark transparent background I will use simple CSS. Also one thing to notice is that the modal overlay occupies the entire browser page’s dimension. We can achieve this by setting the width and height to 100% in CSS. The overlay is
  • 3. supposed to appear over all other controls in the page so that user cannot interact with them in the background. Now, how do I do that? The answer is simple. Once the overlay element is created in java script, we append it to the document body, so it is at the top of the DOM stack and all other elements come below it. This gives it the modal behavior. While the overlay is open you cannot interact with the components beneath it. Also you can specify a higher z-index value in CSS, if you want. Now, let’s check out the java script code and the CSS below, var overlayElement = document.createElement("div"); overlayElement.className = 'modalOverlay'; document.body.appendChild(overlayElement); The CSS .modalOverlay { width:100%; height:100%; position:absolute; top:0; left:0; margin:0; padding:0; background:#000; opacity:0; -webkit-transition: opacity 0.3s ease-in; z-index:101; } Initially the opacity is set to 0. Later, I will set the opacity to a value higher than zero (but less than 1 so that it is transparent) in the script. I will talk about this in a moment. Also another CSS3 property –webkit-transition is set to make the change of opacity smooth. This will give it the fade-in effect. Creating the popup window and displaying the custom message Now that our modal overlay is done, let’s see how to deal with the actual pop up window that will display our custom message.
  • 4. The concept is similar to that of the overlay window we have just created. I will create it in java script and then append it to the body. The custom message will be displayed inside the popup window element using theinnerHTML property. Here is the necessary script, var modalWindowElement = document.createElement("div"); modalWindowElement.className = 'modalWindow'; modalWindowElement.innerHTML = msg; modalWindowElement.style.left = (window.innerWidth - 200) / 2 + "px"; document.body.appendChild(modalWindowElement); The fourth statement modalWindowElement.style.left positions the popup in the center of the page horizontally. Now, let’s see the CSS for our popup window. .modalWindow { position:fixed; top:150px; margin:0; border:2px solid #fff; width:180px; /*height:30px;*/ text-align:center; word-spacing:2px; line-height:15px; font-weight:bold; font-size:13px; color:#fff; padding:10px; opacity:0;
  • 5. z-index:102; background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #7c9bc0), color-stop(2%, #416086), color-stop(100%, #293e56)); -webkit-border-radius:8px; -webkit-box-shadow:-1px 2px 12px rgba(0, 0, 0, 0.91); -webkit-transition: opacity 0.3s ease-in; } The last four style rules are meant for background gradient color, rounded corners, and drop shadow and then I have added a transition to the opacity of the popup to give it a fade effect. Adding the fade effect To add the fade-in effect to both the overlay and the popup I set the opacity to a value higher than 0. You can see in the script below, I have set an opacity of 0.4 to the overlay to make it transparent. The popup window gets opacity of 1 as expected. This change in opacity from earlier values of 0 will trigger the transition that we have set in CSS and will make the change happen over time and smoothly. This gives it a fade-in effect. setTimeout(function() { modalWindowElement.style.opacity = 1; overlayElement.style.opacity = 0.4; overlayElement.addEventListener("click", hidePopUpMessage, false); }, 300); I have added a timeout value of 300ms so that the change in opacity happens after the elements have been added to the DOM and rendered properly. If you are still not clear about fade effects in CSS3, you can go through a dedicated tutorial on it from one of my earlier post, here. Creating rounded corners, gradient background, and drop shadow These can be done very easily now with CSS3. So I will not explain much. You can go through my blog and find out enough materials on it. These effects give the popup window a realistic look and a 3d effect, as if it is floating over the browser window. Hiding the popup window Now that the popup window is displayed, we also need to hide it. The process is simple and just the reverse of displaying it. When you tap outside the popup it is hidden. So I have a specific function for it that is called when user taps on the overlay outside the popup window. Inside the function I set the opacity to 0 again, to give it a fade-out effect and then remove the elements from the DOM. You can check out the code along with the full script below, <script type="text/javascript">
  • 6. var overlayElement = null; var modalWindowElement = null; window.addEventListener('load', initApp, false); function initApp() { setTimeout(function() { window.scrollTo(0, 1); }, 10); document.getElementById("popUpBtn").addEventListener("click", function() { showPopUpMessage("TADAAAA !<p>This is my cool pop up window with rounded corners, gradient background and drop shadow.</p>"); }, false); } //show the modal overlay and popup window function showPopUpMessage(msg) { overlayElement = document.createElement("div"); overlayElement.className = 'modalOverlay'; modalWindowElement = document.createElement("div"); modalWindowElement.className = 'modalWindow'; modalWindowElement.innerHTML = msg; modalWindowElement.style.left = (window.innerWidth - 200) / 2 + "px"; document.body.appendChild(overlayElement); document.body.appendChild(modalWindowElement); setTimeout(function() { modalWindowElement.style.opacity = 1; overlayElement.style.opacity = 0.4; overlayElement.addEventListener("click", hidePopUpMessage, false);
  • 7. }, 300); } //hide the modal overlay and popup window function hidePopUpMessage() { modalWindowElement.style.opacity = 0; overlayElement.style.opacity = 0; overlayElement.removeEventListener("click", hidePopUpMessage, false); setTimeout(function() { document.body.removeChild(overlayElement); document.body.removeChild(modalWindowElement); }, 400); } </script> Conclusion This was a simple tutorial on creating a very nice popup window displaying a custom message. While the focus was based on mobile devices such as iPhone, iPod and other smart phones with web-kit browsers, you can certainly use it for desktop applications as well. The example already runs in Google Chrome and Safari browsers. You can modify it (mainly the CSS) to run on all other desktop browsers as well. Below is the link to the demo once again, check it out in your iPhone/iPod/Android or Blackberry browser. For the full code refer the source. Link: http://jbk404.site50.net/css3/modalwindow/ If you do not have one, check it out in an online iPhone simulator: http://www.iphonetester.com/