Jamie Fearon
Jamie Fearon

Reputation: 2634

Toggling between clicked elements

I have a row of images, when the user clicks on an image then that image is selected. How can I manage to toggle the click event in jquery so that:

1) Only one image can be selected at a time
2) If the selected image is clicked on then it is deselected.

Here's what I have so far, with a fiddle: http://jsfiddle.net/jamiefearon/BY9Fp/1/

$(document).ready(function () {

    var selectedTile = null;

    $('[id^="tile-"]').click(function () {
            $(this).css("background", "red");
            $(this).css("opacity", "0.4");
            selectedTile = $(this).attr("name");
            console.log(selectedTile);
    });
});

Upvotes: 0

Views: 49

Answers (3)

Anton
Anton

Reputation: 32581

Use .siblings()

         $(this).siblings().css({background:"",opacity:1});
        $(this).css({"background": "red","opacity":"0.4"});

demo here http://jsfiddle.net/BY9Fp/11/

Upvotes: 0

BenM
BenM

Reputation: 53198

I would move the styles into a CSS class as follows:

.tile_wrap.selected {
    background: red;
    opacity: 0.4;
}

And then make your click handler something like:

var tiles = $('.tile_wrap');
$('[id^="tile-"]').click(function () {
    if($(this).hasClass('selected'))
    {
        $(this).removeClass('selected');
    }
    else
    {
        tiles.removeClass('selected');    
        $(this).addClass('selected');
        selectedTile = $(this).attr("name");
        console.log(selectedTile);
    }
});

You can see the updated jsFiddle here.

Upvotes: 1

dfsq
dfsq

Reputation: 193261

Improved version of your code:

var $tiles = $('.tile_wrap');
$tiles.click(function() {
    $(this).toggleClass('active');
    $tiles.not(this).removeClass('active');
});

Improvements making your code simplier and more efficient:

  • Cache frequently used elements, e.g. $titles;
  • Select elements by class instead of [id^="tile-"], this will be more efficient;
  • Don't use css method. Use addClass instead.

http://jsfiddle.net/dfsq/BY9Fp/8/

Upvotes: 0

Related Questions