Search code examples
javascriptjqueryhtmlcssmedia-queries

Responisve design is not responding


I am new to responsive designs and am trying to use media queries. I am trying to make my navigation bar responsive using media queries. The problem is when I size the page in a mobile view the navigation bar displays the SPAN tag but it should drop down the menu list once it is clicked on. I attempted to use jQuery for this process. My code is below:

HTML CODE

<span class="menu-trigger">MENU </span>
<nav class = "nav-main">          
  <ul>
    <li>
      <a href = "#" class = "nav-item"> HOME</a>                              
    </li>
    <li>
      <a href = "#" class = "nav-item">ABOUT US </a>
    </li>
    <li>
      <a href = "#" class = "nav-item">PORTFOLIO </a>
    </li>
    <li>
      <a href = "#" class = "nav-item">SERVICES </a>
    </li>
    <li>
      <a href = "#" class = "nav-item">CONTACT US </a>
    </li>
  </ul>
</nav>

CSS CODE

.nav-main {
    width:100%;
    background-color: #222;
    height:70px;
    color:#fff;
}

@media screen and (max-width: 480px){    
    .menu-trigger{
        display:block;   
    }    
    .nav-main > ul > li{
        float:none;
        border-bottom: 2px solid #d5dce4
    }
    .nav-main {
        display:none;   
    }       
    .nav-main > ul > li:last-child{ 
        border-bottom: none;
    }         
}

JQUERY CODE

<script type ="text/javascript">
    jQuery(".menu-trigger").click(function(){
        jQuery(".nav-main").slideToggle();
    });
</script>

Right now when going on mobile size the content nav-main does disappear and only display the SPAN but when the SPAN is clicked on it is supposed to have a toggle effect displaying the rest of the list in the navbar but nothing seems to happen.

UPDATE --- JSFIDDLE - https://jsfiddle.net/k4ytvyef/


Solution

  • Without seeing the placement of your scripts, I can only assume that you may have placed the jquery code above your html elements.

    Trying this out on jsbin, your code works when the jquery selector is able to find the element after it has been loaded.

    To achieve this without moving your code to the bottom of the page, you can wrap your script with jquery's ready event like so:

    jQuery( document ).ready(function() {
       jQuery(".menu-trigger").click(function(){
            jQuery(".nav-main").slideToggle();
    
        });
    });
    

    Edit:

    To the comment above asking why it doesnt work on jsfiddle:

    JQuery is not native javascript. In order to have this work on any test environment, you need to add the jquery library so it can run it along with your code.