mcpolo mcpolo - 4 months ago 28
jQuery Question

I have to click twice to activate function using jQuery

I am having a lot of trouble with jQuery. I have to click twice on a button to make the page disappear. I have tried importing both versions of jQuery and I tried to use the fadeOut() function on different elements, but nothing has prevailed. It works the second time I click, but never the first. This is a recurring problem, and I need to know how it can be fixed. Here is my code:

HTML:

<body>
<h1>CSS3 Buttons Showcase</h1>
<a href="#" id="btn-1" onclick="fadeBg()">Click Me!</a>
</body>


JavaScript:

function fadeBg(){
$("#btn-1").click(function(){
$("body").fadeOut(1000);
})
}

Answer

You must change your function to:

function fadeBg(){          
      $("body").fadeOut(1000);    
}

In your html code you have is seting on event click to run your function fadeBg. so on your function you must put what you want to run, on this case $("body").fadeOut(1000);