Modal with HTML, CSS and JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up coders hope you're doing well today we are learning how to create a model from scratch with HTML CSS and JavaScript a model is this pop-up box usually positioned on top of everything else in the document and it is used to attract the user's attention to some special information or to ask the user to do something for example to register or login without navigating to another page it is a commonly used component in websites and that's why I thought it would be a good idea to implement it from scratch as an alternative to using some third-party library or framework for this purpose I hope you guys will enjoy this video and get some value out of it don't forget to share like subscribe and without further ado let's go okay starting with an empty project in our editor I'm using the visual studio code editor let's create a index dot HTML style dot CSS and main dot J's files in our project folder in the index.html file I type exclamation marks as M at abbreviation es code comes with the MA plug-in embedded and if I hit tab or enter we get some html5 boilerplate code let's insert the title models and Link the external files to the document first the stylesheet yeah we are and the javascript file notice that instead of placing the script in the body right above the closing body tag I placed it in the head using the dafair attribute and we can now proceed to defining the body markup for starters let's add a model triggering button so upon a click event over this button the model will pop up other common model triggering events would be on page load or wild scrolling or onmousemove or when the user is about to leave the page etc and now let's create the model I usually like placing the models at the end of the page before the closing body tag of course in this case we don't have much content but even if we did I would still keep all page models together towards the end of the page after the main content now regarding the mark-up for the model we have a div with a class method this will actually be the background overlay and it will contain a div with a class of content which will be the actual model box and in here goes the content for the model we could for example follow the bootstrap framework structure by separating model content into model yeah there model body and model footer however let's keep things even more basic and generic and flexible by simply adding all content in here without separating it into sections so let's add an h1 heading with a title model Idol and a few paragraphs with lorem ipsum text very nice and let's add a few more words to the second paragraph lower them and let's say ten more words and finally let's add a close button let's place it here although it doesn't really matter since it will eventually be absolutely positioned relative to the model content I'll be using a span element instead of a pattern with the class modal lows and instead of using the letter X here which depends on the phone family and the lines might not be exactly perpendicular let's use the character entity representing the multiplication sign and that's all regarding the mark-up for the model so we have a div with a class which is actually the background overlay containing a div with the class model content which is the actual model box with some content okay now let's open the project in the browser for this purpose I'm using the live server which is a Visual Studio code extension and allows for live reloading so this is what we've created up to this point and let's proceed to styling with CSS for starters I will paste some basic styling not related to the model in order to save some time so we are importing the montserrat own family resetting margin and padding to zero and box sizing to water box for all elements setting phone family background color and color for the body and some basic styling for the button setting margin and padding and cursor to pointer so if we save this is what we get and let's proceed to styling the model starting with the model background overlay let's first define background color so that we can easily see what's happening and let's set it to RGB a zero zero zero and if we set opacity to 1 then we get a solid black color but let's set it to point five making it semi-transparent now we want the background overlaid who covered the entire viewport so let's set position to fixed relative to the viewport starting from the top left corner and expanding to the entire viewport width and height and by the way the reason we used a fixed position for the model instead of absolute is so that it always remains visible even in case of page scrolling so if we set position to absolute for the model and let's set a minimum height for the body to 200% of the port height we can see that on page scroll model is also moving however if we set position to fixed we can see that model always remains visible although we could also disable page scrolling by setting overflow to hidden for the body when model is displayed and we probably will do this later with JavaScript now let's also define a set index in order to ensure that model sits on top of other content that index could be 1 or 10 or a thousand depending on what other z-index values exist in our page let's also set overflow to Otto in order to enable scrolling if needed although this is not really necessary since we are going to take care of overflow in model content and finally we will use flexbox in order to position the model content for this purpose we will set the display property two flags for the model of course eventually we will set display property to none and we will use javascript in order to set it to flags whenever the model is triggered in order to horizontally Center the model content let's set justify content ooh Center of course this will become more obvious once we define dimensions for the model content which is actually the model box and in order to vertically align the model content we will use the a line items property and if for example we wanted to Center it we would set it to center but let's set it to flex start instead in order to align it at the top of the container okay now let's proceed to styling the model box the model content and let's start by setting background color to white next let's set width to sixty percent of its parent elements width which in this case coincides with viewport width instead of fixing the height let's set a maximum height ooh 75 percent let's also add some margin and let's set it to two REM and some padding again to REM and let's also round the corners a bit by setting porter radios 2.25 REM let's also add box-shadow with zero pixels horizontal offset four pixels vertical offset 20 pixels blur radius so if for example this was zero this is what we would get and this is the color if for example we set opacity to one then we would get a solid black color and therefore box shadow would be more intense and finally let's set overflow to auto so that scrolling will be enabled in case of content overflow so if i zoom in initially height will increase until we reach the maximum height which is 75% and from that point on we will get a scrollbar if we didn't set overflow to auto then overflowing content would expand beyond the boundaries of the box since the default value for overflow is visible okay we are actually done with styling the model box let me paste some basic internal styling for the h1 heading and the paragraphs nice and let's proceed to styling the model close button for starters we will absolutely position it relative to model content to the top right corner of model content and let's increase font size 1.75 REM and let's set font-weight:bold let's also set Harding to 0 for top and bottom and point 75 REM or left and right color will be black with low opacity let's say point two cursor will be pointer and let's also set user select to none in order to make it an selectable since we are only interested in clicking the button and not selecting it and finally on model close button for where and focus let's change color by slightly increasing opacity to 0.5 okay I think we are done with CSS styling for now but let's also add some very basic responsiveness for smaller screens I will just paste this part in order to save some time I will of course include a link in the description to this project in case you want to have a closer look and now let's set the display property of model to none instead of flags and we will use javascript in order to show or hide the model so let's proceed to JavaScript for starters let's store the involved elements in two variables for easier access first the model trigger pattern since we currently only have one button element this should be okay for now however later we will be a bit more specific and similarly we get the model and model close button elements and store them into the corresponding variables next we will add an event listener for a click event over the model trigger button element and whenever the model trigger button is clicked the following anonymous function will be executed and let's use arrow function notation and in this case we want to set the model display property to flex let's save and check the result indeed on button click model is displayed and we could also remove page scrolling while model is being displayed by setting their overflow property for the body to hidden let's do this you and now page scrolling is not available while model is being displayed okay now let's handle the model close button click event you in this case we want to close the model and set the overflow property for the body back to its default value in other words we want to do the opposite things by setting the display property for the model to none and the overflow property for the body to Anisha okay let's check the result by clicking on the model trigger button model is displayed and body overflow is set to hidden and by clicking on the model close button model is hidden and body overflow is set back to its default value which is visible excellent we can now open and close the model next step is to also be able to close the model upon a click over the background overlay and not the model box itself but first in order to avoid repeating staff let's create a function called toggle model which will be responsible for opening or closing the motor so in here we first want to check whether the model is currently open and in this case close it one way to do this would be by checking whether its display property is set to flex so let's use the get concluded style method which is a window object method however this part is implied so we can ignore it or the model and we are interested in the display property and if this value is equal to flex this means that model is currently open and therefore we want to close or hide it so let's copy the code related to closing the model and paste it in here else in this case the model is currently closed and therefore we want to open it so let's copy the code related to opening the model and paste it in here and we can now replace this part with a call to the toggle modal function and similarly for this part and we could even remove the brackets now since they are not necessary okay and let's make sure that we didn't break anything and everything still works as intended so we can still open the model by clicking on the model trigger button and we can close the model by clicking on the model close button nice now let's also make it possible to dismiss or close the model by clicking on the model background overlay or these purpose we will add an event listener over the model element for a click event and whenever there is a click event the total model function will be called however this is not exactly correct yet and let me show you what I mean so by clicking on the background overlay indeed model goes away however it also goes away by clicking on the model box and this is happening due to event bubbling since despite the fact that event was initiated on the model box the model content it will move up the dome hierarchy eventually triggering the event attached to the model element so before calling the local model function we somehow want to ensure that the click event actually occurred over the background overlay one way to do this would be by checking whether the event target which is the element that was actually clicked contains the class model and let's check the result clicking on the background overlay closes the model but clicking on the model box does not close the model so it works another way to do this would be by checking whether event dot current target which always refers to the element on which the event listener is attached to is equal to event dot target and let's put this into one line in order to save some space and check the result indeed by clicking on the model backdrop the background overlay model goes away however nothing happens when clicking on the model box so everything works as intended okay bye now we have a functioning basic model what's next well instead of instantly opening and closing the model we could smoothen the experience by animating it so let's do this back to our CSS and now theoretically one way we could go about this would be by using transitions for example changing opacity from 0 to 1 and vice versa however we cannot do this since we are changing the display property so we will use CSS animations instead and more specifically we will bind animations to specific classes and add or remove these classes accordingly in order to get the desired result for example by adding the modal show class over the model element the element with the class model the following animation will take place let's name the animation faith in we will specify the keyframes for the animation in a bid animation duration will be point five seconds animation timing function is in out we will not set delay iteration count and direction and animation film mode will be set to forwards in order to retain the style values set by the last keyframe and let's specify the key frames for the fade in animation and this is I suppose as simple as it gets starting with opacity zero we want to end up with opacity one and all that remains now in order for the model to fade in is to use JavaScript in order to add the model show class to the model whenever the model is about to be displayed so back to our JavaScript file this is the part where we want to open the model and additionally to setting its display property to flex let's add the model show class ok let's check the result indeed by clicking on the model trigger button we get the faith in animation and similarly we could add an exit animation so let's move back to our CSS file and define the model height class which will trigger the fade-out animation and let's keep this animation a bit shorter whenever added to the model element and let's specify the key frames for the fade-out animation this time we want to start with opacity one and end up with opacity zero now back to our javascript file this is the part where we want to close the model so here's where we will add the model height class however this way model will close instantly since we are also setting the display property to none so we should add a small delay before executing these lines of code we can do this using the set timeout function delay will be 200 milliseconds since this is the duration of the fade-out animation and let's also not forget to remove the animation related classes so that we can add them again and so on and let's see the result indeed model fades in and out now we could also specifically target and animate the model box and let's quickly do this back to our CSS file I will copy this part since we are going to work in a similar manner and paste it over here right below the model content element styling and now whenever the model show class is added to the model element the following animation will also take place over the model content element which is the model box let's name the animation faith in down we will specify the keyframes for the animation in a bit let's keep everything else the same notice that we didn't add any new class since the presence of the model show class or edition of the model show class should I say is enough to trigger both animations they one related to the model as well as the one related to the model content and similarly whenever the model height class is added to the model element they fade out up animation will be applied to the model box the model content now let's specify the keyframes first for the faith in down animation and initially we set the opacity for the model box to zero and we also want to slightly pull it up by using the translate y CSS function over the transform property so let's pull it up by three REM and eventually we want to set the opacity for the model box to 1 and also push it back down to its original position by setting translate Y to 0 and doing the exact opposite for the fade-out up animation we start with opacity 1 and translate y 0 and end up with opacity 0 and translate y -3 REM okay let's see what we've created indeed on entrance model box fades in and slides down and on exit it fades out and slides up I suppose alternatively we could simply slide down and up the model box without changing opacity so let's try this and see how it looks it's a subtle difference maybe this way is a bit better and guys feel free to experiment and use your imagination and creativity in order to come up with awesome model entrance and exit animations okay let's restore the change in opacity and I would like to keep the entrance animation for the model box a bit shorter 2.3 seconds and now regarding the fade in and fade out animations over the model element which also includes the background overlay let's keep them really short 4 into 1 seconds so for example the faith in animation will be completed in point one seconds and the faith in down animation of the model box will continue 4.2 more seconds in total point three and regarding the fade-out animation let's not forget to add a small delay of 0.1 seconds so that we allow the model box fade-out up animation to take place before the model is hidden okay before checking the final result let's do some tidying by gathering all animations and keeping them together towards the end of the file you nice and by the way 50% wait for model content would be better I think and let's check the final result okay let's leave it here now one last thing I would like to discuss is the case where we have more than one models in our page and there is actually a very good chance we will so let's move back to our HTML file and create two more models for these papers i will copy pasted the first model two more times simply changing the title in order to distinguish them to model title one two and three and let's also create two more model triggering buttons and change the text to show model one two and three now we somehow want to link the triggering buttons to the corresponding models for example we want to know that by clicking on the first button this model will be triggered for this purpose we will first specify IDs for the models using the ID attribute and let's set the ID for the first model to model one or the second model to model to and for the third model to model three and in order to specify it to which model each button refers to we will use a data attribute and let's call the attribute data model target and set its value to the ID of the corresponding model for example if we want this button to trigger this model the model with ID model 1 then this should be the value we should set its model target attribute to so by clicking this button we will use JavaScript in order to extract the value of the data model target attribute and trigger the corresponding model similarly we want this button to target the model with ID model 2 and this button to target the model with ID model 3 okay that's all with HTML and now let's move back to JavaScript and do the necessary modifications for starters we now want to select all model trigger buttons and models and model close buttons by using the query selector all method which returns a node list containing all documents elements that match the specified selectors regarding the model trigger buttons instead of using the button selector we could be a bit more specific and for this purpose we could make use of the data model target attribute so by using this selector we are selecting all elements in the document which have the data model target attribute next step is to add event listeners to the elements so starting with mortal trigger patterns we will use their for each method in order to go through each element in the note list in this case each element represents a model trigger pattern and for each model trigger pattern we want to add this click event listener so let me cut this part paste it in here and replace the model trigger button with LM we will return to the taco mortal function call in a bit but let's first quickly do the same for model clothes buttons and models you now regarding the toggle modal function we now have to specify which model we want to toggle since we have more than one models for this purpose we will add a parameter to the function and let's call the parameter model ID so the ID string of the model will be passed into the function as an argument when it is called and now the only modification we have to do in order for this to work is to get the specific model using the ID and for these Purple's we can make use of the get element by ID method and store it into a variable called modem and that's all we are done with a toggle modal function all that remains now is to pass the model ID as an argument when the function is called in order to get the model ID when a model trigger button is clicked we have to access its data model target at a good value so let's use event dot current target although in the case of this button current target and target will always coincide since it doesn't contain any other elements and we will make use of the get attribute method in order to get the value of the data model target attribute next when a mortal close button is clicked we want to access the ID of the model it belongs to and one way to do this is by using the closest method over the clicked close button in here goes the selector we are looking for the closest model and we want to extract the ID property value and finally on a click event over the model in this case we are specifically targeting an event over the model Batroc we can directly access its ID okay let's check the result and let's open model three nice and model two works like a charm and let's see we get any errors in the console no errors nice one last thing you might wanted to add is the possibility for the user to dismiss or close the model when they press a specific key on the keyboard for example the Escape key so let's quickly do this we first need to add an event listener over the document for the keydown event and if the escape key was pressed in other words if event dot key code equals to 27 but before closing the model we also want to make sure that the model is currently open one way to do this is by checking whether an element with a class modal combined with a class mortal show exists if this does not exist it will be set to none and therefore this expression will be false and all we have to do now in order to close the open model is called the toggle model function passing its ID as an argument notice that in order for this to work as intended we assume only one model window open at a time which is a reasonable assumption since I don't think that more than one models open at the same time would be a good user experience okay let's check if this works by opening a model and pressing various keyboard keys nothing happens but if I hit escape indeed model goes away and if I keep pressing escape while no model is open nothing seems to be happening also no wearers in the console so I think we are good and let's not expand any further guys I hope by now you feel confident enough to go ahead and create all sorts of models according to your style and needs based on this project I've also created a few more model examples mainly just by tweaking the model CSS styling and maybe the entrance and exit animations I didn't change anything regarding the JavaScript part though I will of course include a link in the description to this project as well I really hope you guys enjoyed this video and got some value out of it if you did please hit the like button and feel free to share the video with anyone who might be interested I would also love to hear your thoughts in the comment section below don't forget to subscribe if you want more you next time keep coding keep improving and enjoy the journey take care bye
Info
Channel: Coding Journey
Views: 6,114
Rating: undefined out of 5
Keywords: modal, modal html css javascript, modal with html css and javascript, modal html css js, modals, html modal, modal window, popup box, modal popup box, popup box html css javascript, web component, javascript modal, create a modal html css javascript, how to create a modal, css modal, html popup, javascript popup, modal popup, modal animation, how-to, html, css, javascript, ui, ux, tutorial, web tutorials, web development, front-end tutorial, coding journey, modal web development
Id: YARYSKySwhg
Channel Id: undefined
Length: 40min 18sec (2418 seconds)
Published: Sun Nov 10 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.