user2958571
user2958571

Reputation: 133

Jquery fadeIn image

I have few images and when one of them is pressed i want the other ones to fade out.

<body>
    <script src="Scripts/jquery-2.0.3.min.js"></script>
    <img class="images" id="img" src="/images/user1.png" height="100" width="100">
    <img class="images" id="img2" src="/images/user2.png" height="100" width="100">
    <img class="images" id="img3" src="/images/user3.png" height="100" width="100"><br>

    <script>
        $(document).ready(function () {

            $('#img').mouseover(function () {
                $(this).css('cursor', 'pointer');
            });
            $('#img2').mouseover(function () {
                $(this).css('cursor', 'pointer');
            });
            $('#img3').mouseover(function () {
                $(this).css('cursor', 'pointer');
            });
        });

        $(document).on('click', '.images', function (event) {
            $(event.target.id).fadeIn(1000);
            $(".images:not(#" + event.target.id + ")").fadeTo("fast", 0.5);

        });


    </script>


</body>

the problem is that when i press on a different image from the first i pressed all the images stay fadeout. it looks like the fadein i added for the pressed image doesn't work.

Upvotes: 0

Views: 97

Answers (4)

user2211216
user2211216

Reputation: 375

i think closer answer to your question is:

 $("#"+event.target.id).fadeTo("fast" , 1);
 $(".images:not(#" + event.target.id + ")").fadeTo("fast", 0.5);

Upvotes: 0

ntdb
ntdb

Reputation: 431

Two things to note:

  1. "$(event.target.id)" is not a valid selector. You could write "$('#' + event.target.id)" but "$(event.target)" is much easier.
  2. The jQuery "fadeIn" function will only fade from opacity:0 to opacity:1, not to or from any other value.

What you end up with:

$(document).ready(function () {
    $('img').click(function(event) {
        $(event.target).fadeTo(500, 1.0);
        $('img').not(event.target).fadeTo(500, 0.5);
    });
});

Here's a working fiddle

Upvotes: 1

j08691
j08691

Reputation: 207901

I'd recommend scrapping your code and doing this:

CSS

.images {
    cursor:pointer;
}

jQuery

$(document).on('click', '.images', function () {
    $('.images').not(this).fadeTo("fast", 0.5);
    $(this).fadeTo(1000,1);
});

jsFiddle example

Upvotes: 0

Anton
Anton

Reputation: 32581

You need to make the one you are clicking on to fadeTo("fast",1)

$(document).on('click', '.images', function (event) {
    $(".images:not(#" + event.target.id + ")").fadeTo("fast", 0.5);
    $(this).fadeTo("fast", 1); // This is the new line
});

DEMO

Upvotes: 0

Related Questions