0

I am trying to create a drop down menu list using jQuery and simple CSS at this Demo the sliding works fine but I don't know why on click function the page also refreshes (this is more obvious when you look at the enter image description here Here is the code I have:

<style>
.musthidden{display:none;}
</style>

<ul>
    <li><a href="#">One</a></li>
    <li id="two"><a href="#">Two</a>
                  <ul class="musthidden">
                    <li><a href="#">Two _ 1</a></li>
                    <li><a href="#">Two _ 2</a></li>
                    <li><a href="#">Two _ 3</a></li>
                    <li><a href="#">Two _ 4</a></li>
                  </ul>
    </li>
    <li><a href="#">Three</a></li>
    <li><a href="#">Four</a></li>
</ul>

<script>
 $("#two").on("click",function(){
    $(".musthidden").slideToggle();
 });
</script>

Can you please let me know why this is happening?

3
  • I'm not seeing any reloading in your fiddle. Commented Apr 14, 2014 at 21:05
  • Me neither - Windows8 IE11 Commented Apr 14, 2014 at 21:05
  • I'm seeing it in Chrome. Watch the favicon in the corner when you click the #two li. It's reloading because of the inner <a> (anchor) tag. The reason, you're not seeing it is because it's in an <iframe />. Commented Apr 14, 2014 at 21:17

2 Answers 2

3

click function should be:

$("#two").on("click",function(e){
    e.preventDefault();
    $(".musthidden").slideToggle();
 });

e.preventDefault() says: do not carry out any other functions binded to this event, stop after hitting this function. So it shouldn't do anything after.

e is event object that gets sent through the click event, most other events also have e

see updated fiddle without any refresh.

Sign up to request clarification or add additional context in comments.

Comments

0

You should use prevent.default() function. Like this:

 $("#two").on("click",function(e){
  e.preventDefault();
  $(".musthidden").slideToggle();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.