Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 967
spike Avatar asked May 07 '13 16:05

spike


People also ask

What is jQuery is used for?

jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.

Is jQuery used anymore?

jQuery is one of the longest-running and most influential JavaScript libraries on the web. A staggering 78% of the top 1 million websites use jQuery in some way, according to BuiltWith. As for the most talked-about JavaScript library today, React, it's used by a relatively paltry 14%.

Which is better js or jQuery?

Pure JavaScript can be faster for DOM selection/manipulation than jQuery as JavaScript is directly processed by the browser and it curtails the overhead which JQuery actually has. JQuery is also fast with modern browsers and modern computers. JQuery has to be converted into JavaScript to make it run in a browser.

Is jQuery the same as JavaScript?

The main difference among the three is that JavaScript is client-side, i.e., in the browser scripting language, whereas jQuery is a library (or framework) built with JavaScript.


2 Answers

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.

like image 108
PSL Avatar answered Sep 30 '22 13:09

PSL


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 !

like image 34
Pini Cheyni Avatar answered Sep 30 '22 13:09

Pini Cheyni