0

I have the following HTML:

  <span class="thumbnav" id="?"><?php get_the_image(); ?></span>
  <span class="thumbnav" id="?"><?php get_the_image(); ?></span>

  <div class="?" style="display:none;">
       Some image, and a bit of text are staring at you.
  </div>

  <div class="?" style="display:none;">
       Some image, and a bit of text are staring at you.
  </div>

My goal is to use jQuery to find the ID value for every <span>, then use that ID to set a .click() event that will trigger a .show() function on the <div> elements.

So far I have this:

var clasid = $(".thumbnav").attr("id");

 $("#" + clasid).click(function () {
 $("." + clasid).show();
});

Which works, but only for the first <span>.

So I was wondering if there is a way to make this script work for all the spans, I read the jQuery documentation and they suggest using either .map() or .each(), but I haven't been able to figure it out.

Also it would be great if anyone could give me a hint on how to hide a <div> that was active when a new <div> is being displayed.

Thanks!

1
  • 2
    That's because you cannot have same id for multiple elements. Id must be unique. Use classes instead for the purpose Commented Jul 8, 2014 at 5:18

2 Answers 2

2

you can write class event and dynamically access that element id:

$(".thumbnav").click(function(){

$("." + this.id).show(); // this.id will give you clicked element id

})

See FIDDLE EXAMPLE

Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant! So basically 'this' selects the current object? Sorry for being so ignorant, novice here.
yes you are right $(this) will give you jquery object and this will give you javascript
2

You can simply bind them using:

$(".thumbnav").click(function () {
 $('.'+this.id).show();
});

Comments