Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*The media_action, works as the function that is executed when the screen is less than the selected amount, like 979px such as this case */
- function media_action(x) {
- //This var gets the trigger element
- var titles = document.getElementsByClassName("head-4"/*You place here the class of the trigger, you can also use a tag or id*/)
- //this conditional checks the width of the screen and see if it matches the selected amount
- if (x.matches) {
- let i;/*This is a simple loop for the classname*/
- for(i = 0; i < titles.length; i++){
- //Here we add an event listener on click, and call the function we define later
- titles[i].addEventListener("click", display_child)
- }
- } else {
- let i;//same loop as before
- for(i = 0; i < titles.length; i++){
- /*In this part we especify what will happen when the screen stops matching with the selected width, in this part, i remove the event listener that i added on line 12*/
- titles[i].removeEventListener("click", display_child)
- }
- }
- }
- /*This is for future matters, i used this var to toggle beetween the display list as you can see on the next function*/ var toggle = 0
- //This is the function that is triggered when the screen reaches the selected width
- function display_child(e) {
- /*In this 2 variables we get the children elements of the parent*/
- var get_parent = e.target.parentElement//Here we get the parent of the desired element
- var get_children = get_parent.children//We use this function to get all the children of the parent
- //another way to call this is to get all sibling elements
- let i//This is a loop of the parent childrens or siblings if you like
- for (i = 0; i < get_children.length; i++){
- //In this conditional we set the element we wish to target
- if(get_children[i].tagName.toLowerCase() == "ul"/*I use this to target the first ul tag of the parent childrens/siblings*/){
- //This action is on your desire, you can perform any action you wish on the selected element
- if(toggle == 0){ get_children[i].style.display = "block"
- toggle = 1//as you can see, i used the toggle variable to toggle the display on the ul
- }
- else {get_children[i].style.display = "none"
- toggle = 0}
- }
- }
- }
- var media_listener = window.matchMedia("(max-width: 979px)")//in this matchMedia we specify the screen width you'll use to make the function
- media_action(media_listener) // Call listener function at run time
- media_listener.addListener(media_action)//This is the listener that's going to trigger the media_action as soon as it matches the width size
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement