David Lazar
David Lazar

Reputation: 63

How to use a variable for toggling multiple elements

I have a code which takes a data-text attribute from an image or a div and displays it as a description in a different div. I am using a variable to determine whether the text is showing or not. This is a problem when having more elements as the variable is shared by all the togglable elements. I want the code to work with all the divs/images that have the classes assigned but I don't know how to fix the problem with a variable. Please see the jsfiddle for better understanding of what I'm on about.

var toggled = 0;

$("#main > .item").click(
  function () {
    if(toggled == 0){
      var currentext = $(this).data("text");
      $(this).parent("div").children("div.text").text(currentext);
      toggled ++;
    }
    else{
      $(this).parent("div").children("div.text").empty();
      toggled --;
    }
});

Upvotes: 1

Views: 55

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388416

use

$("#main > .item").click(function () {
    var $this = $(this);
    if($this.data('toggled')){
        $this.parent("div").children("div.text").empty();
        $this.data('toggled', false);
    }
    else{
        var currentext = $this.data("text");
        $this.parent("div").children("div.text").text(currentext);
        $this.data('toggled', true);
    }
});

Demo: Fiddle

Upvotes: 2

Denys Séguret
Denys Séguret

Reputation: 382314

You could use the data function to attach the number to the element :

$("#main > .item").click(
  function () {
    var toggled = $(this).data('toggled')||0;
    if(toggled == 0){
      var currentext = $(this).data("text");
      $(this).parent("div").children("div.text").text(currentext);
      toggled ++;
    }
    else{
      $(this).parent("div").children("div.text").empty();
      toggled --;
    }
    $(this).data('toggled', toggled);
});

Demonstration

Upvotes: 3

Adil Shaikh
Adil Shaikh

Reputation: 44740

Try this -

$("#main > .item").click( function () {
    if ($.trim($(this).next('.text').text()) == "") {
        var currentext = $(this).data("text");
        $(this).next('.text').text(currentext);
    } else {
        $(this).next('.text').text("");
    }
});

Demo ---> http://jsfiddle.net/ws3FQ/5/

Upvotes: 0

Related Questions