spike
spike

Reputation: 10004

jQuery '#' + data("target") pattern

I've seen this a bunch:

<a href="#" id="trigger" data-target="content">Click me</a>
<div id="content">And something will happen here</div>

With JS like this:

$("#trigger").click(function(){
  $("#" + $(this).data("target")).hide();
})

It looks a little weird to me to be doing this string concatenation to create selectors which are then used to get the target element. Is there a better pattern in Javascript (with jQuery available) for setting up handlers on one element which need to know about another target element?

Upvotes: 15

Views: 88324

Answers (6)

Sayantan Dey
Sayantan Dey

Reputation: 27

$(this).attr('data-target', '#myTarget');

this worked for me

Upvotes: 0

Pini Cheyni
Pini Cheyni

Reputation: 5437

You can simply use

$('#content').modal('toggle');

Any where in you're code to initiate the modal show and hide, You can use even "show"/"hide" functionality directly.

I assume you're using Bootstrap and one of the latest versions of jQuery.

Enjoy !

Upvotes: 4

PSL
PSL

Reputation: 123739

Why you do string concatenation just store the id with #

<a href="#" id="trigger" data-target="#content">Click me</a>

$("#trigger").click(function(){
  $($(this).data("target")).hide();
})

Similarly you can store any selectors as is in data-target say for ex:- .tab1 etc so that you do not have to perform string concatenation again inside the click or any event.

Upvotes: 32

Kevin B
Kevin B

Reputation: 95017

I would skip the data- completely, thus allowing graceful degradation.

<a href="#content" id="trigger" data-target="">Click me</a>
<div id="content">And something will happen here</div>

with

$("#trigger").click(function(e){
  e.preventDefault();
  $( $(this).attr("href") ).show();
  // note, i'm purposly not using this.href due to a bug in IE that would return the entire href rather than just the hash
})

Upvotes: 0

Gabe
Gabe

Reputation: 50493

Why not do something like this, a much better approach in my opinion:

// Set the target
$("#trigger").data('target', $('#content'));

// Get the target
$("#trigger").click(function(){
  $(this).data("target").hide();
})

If you're setting it from the backend, I would include the hash with the attribute value as others have suggested.

<a href="#" id="trigger" data-target="#content">Click me</a>

$("#trigger").click(function(){
     var target = $(this).data("target"); 
     $(target).hide();
})

Upvotes: 3

tymeJV
tymeJV

Reputation: 104775

You always have the option to build the selector, looks a bit nicer than concatenating the string inside the selector.

$("#trigger").click(function(){
    var selector = "#" + $(this).data("target");
    $(selector).hide();
});

A little nicer, not sure if it's what you're looking for.

Upvotes: 1

Related Questions