Home > Mobile >  Why is using multiple methods next to each other not working in jQuery?
Why is using multiple methods next to each other not working in jQuery?

Time:12-29

I'm new in jQuery and came across a problem. When I want to use multiple methods next to each other the code won't work. Here is the code:

$("document").ready(function() {
  $("#button1").click(function() {
    $("#home").fadeTo(1000, 0.5).delay(1800).fadeIn(500);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="img.png" alt="list image" id="menu">
<br/>
<nav>
  <ul>
    <li id="home"><a href="#">Home</a></li>
    <li id="contact"><a href="#">Contact</a></li>
    <li id="about"><a href="#">About</a></li>
  </ul>
</nav>

<br/>
<button id="button1">Button1</button>

I have changed the delay from 800 to 1800 because I thought that the delay would start when it's clicked. And also because the .fadeTo has a speed of 1000 ms. But unfortunately it didn't work. After that I had rewritten the code.

$("document").ready(function(){
   $("#button1").click(function(){
       $("#home").fadeTo(1000,0.5,function(){
           $(this).delay(800).fadeIn(1000,1.0);
        });
    });
});

This didn't work either. So eventually I changed .fadeIn to .fadeTo. That worked! So now, because of this I got a few questions that I couldn't answer.

  1. Why was $("#home").fadeTo(1000,0.5).delay(1800).fadeIn(500); not working?
  2. Why does .fadeIn work and .fadeTo doesn't?

CodePudding user response:

The problem has nothing to do with chaining, as you found when you used completion functions instead.

I think the problem is that fadeIn() doesn't do anything if the element isn't hidden; it has effect if the element has partial opacity. Change that to fadeTo(500, 1.0) and it works.

As far as I can tell, this isn't made clear in the documentation. I'm not sure whether this should be considered a bug in fadeIn() or a documentation bug.

$("document").ready(function() {
  $("#button1").click(function() {
    $("#home").fadeTo(1000, 0.5).delay(1800).fadeTo(500, 1.0);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="img.png" alt="list image" id="menu">
<br/>
<nav>
  <ul>
    <li id="home"><a href="#">Home</a></li>
    <li id="contact"><a href="#">Contact</a></li>
    <li id="about"><a href="#">About</a></li>
  </ul>
</nav>

<br/>
<button id="button1">Button1</button>

  • Related