JQuery click listener for class - javascript

I have a class of images in HTML, with IDs img1,img2,...,img9. I want to make links (HTML a tag) with IDs link_img1, link_img2, ..., link_img9 so that whenever I click on a link, the corresponding image appears.
I'm thinking about assigning all the links to the same class, then add a JQuery click listener for that class, and inside the listener, look for the ID of that link, and shows the corresponding image. How do I add a JQuery listener for a class, and how do I get the ID from the element?

You shouldn't use the ids of a tags to define their target.
Better use the href attribute instead:
<img id="img1" ...>
<img id="img2" ...>
Click me
Click me
jQuery("a.image-link").click(function(){
$(this.href).show();
});
This allows you to have two links for the same image.

Try:
$('a.yourClassName').click(function(){
$('img#'+ this.id).show();
});

To add a listener for a class, just select it the jQuery way (i.e. $('elem.class'). Then use attr() to get the id.

Here. As mentioned in some other answers, id is probably not the best way to determine what action you should take. Use another attribute as you see fit
$('a.some-class').click(function() {
switch (this.id) {
case 'one':
// do something
break;
case 'two':
// do something
break;
default:
// do something
break;
}
});

try this
$('a.yourClass').click(function(){
var $linkID= $(this).attr('id');
$('img#'+ $linkID).show();
});

Related

trigger click an element with a specific class and attribute

I have few link elements related to a certain class and assigned row attributes to it and I'm trying to trigger click event based on the attribute value.
<a class="manage_edit_nb" nb_id="1"></a> | <a class="manage_del_nb" nb_id="1"></a>
<a class="manage_edit_nb" nb_id="2"></a> | <a class="manage_del_nb" nb_id="2"></a>
<a class="manage_edit_nb" nb_id="3"></a> | <a class="manage_del_nb" nb_id="3"></a>...
Is it possible to trigger click or any event for a certain attribute value for a certain class?
If I try something similar to
$('a[nb_id = "1"]').trigger('click');
it triggers click event for all elements irrespective of class but I failed to figure out how to put class reference in there!
First, the nb_id is not a valid attribute, use data-id instead. data-* attributes are allowed, and I personally like them. And, they can be accessed using $.attr('data-id') method, and their value can bee updated using $.attr('data-id', 'new value'). Going back to the question, try using below selector
$('.manage_del_nb[data-id="1"]').get(0).click();
OR
$('.manage_edit_nb[data-id="1"]').get(0).click();
Why .get(0)? Assuming that the element has been bound with .click(callback()) or .on('click'), the .trigger('click') will not do anything, so I am using .get(0) to get the DOM object which has that method to simulate the click event. Regardless of being said, you can use trigger('click') the way you're already using
This should work fine.
$('a.manage_edit_nb[nb_id="1"]').trigger('click');
here it is working:
https://jsfiddle.net/link2twenty/g0txnzfw/
The thing that you are trying to do by the above code is triggering a click event on both '.manage_edit_nb' and '.manage_del_nb' selector and hence the event is occuring on both. Try to be little more specific by giving the class name like
$('a.manage_edit_nb[nb_id = "1"]').trigger('click');
I think this is exactly what you need : First of all, change all nb_id to data-nb_id. and use the following code, needs jquery.
$(document).ready(function() {
// Handle click event on the class required
$('.manage_edit_nb').click(function(){
// Get nb_id of that particular anchor event of the class
var nb_id= $(this).attr('data-nb_id');
// Switch on nb_id
switch(nb_id){
// Handle your cases separately here
case "1":
alert('Case 1');break;
case "2":
alert('Case 2');break;
case "3":
alert('Case 3');break;
}
});
});

Element not reacting to JQuery Click

I have added Elements using Jquery inside PHP after loading them from the database. Each button has two classes, one controlling the GUI and another controlling the Click for particular button. The code is as under
echo "<script type='text/javascript'>$('.main').append('<button class=b_ui b$index>Change</button>'); </script>";
Now if I check the classes from Inspect Element perspective of the browser, it shows 2 classes. But when I click on it and get class of element using this code
$('.b_ui').click(function()
{
cls = $(this).attr('class');
alert('no. '+cls);
}
It shows only first class (GUI) and not the other which I want to use for handling click.
Any help ?
Put quotes around the class attribute. <button class=\"b_ui b$index\">Change</button>
You should use "on" method:
$(document).on('click', '.b_ui', function() {
cls = $(this).attr('class');
alert('no. '+cls);
});
When adding elements dynamically to the DOM, they are not accessible by jQuery like an element which was there at page load. say you have this div:
<div id="div"></div>
and you add some content with jQuery so it now looks like this:
<div id="div"><span id="span"></span></div>
you cannot refer directly to the span using jQuery with $('span[id=span]'), you have to target a containing element then filter which contained element you want:
$('#id').on('click','span',function(){});

Best way to assign Jquery events to Dynamic buttons

I am generating twitter bootstrap modals dynamically based on the user action (Long Story). Lets say some times user can see 100 modals on his screen. In each and every modal I have 5 dynamic buttons, each have it own purpose and did same in all modals, and have different id's.
I am attaching onClick events to those buttons by using jquery when ever there is a new twitter modal opens up by using the button id as follows
$(document).on("click","#btn"+btnNumber, function(){
//Code Goes Gere
});
So If I open 100 modals, each have 5 buttons, Is it good idea to assigning click events for 500 times ?
or Is it good Idea to assign click events by using it's name attribute for 1 time as follows
$(document).ready(function(){
$(document).on("click","btnNameAttr", function(){
//Code Goes Gere
});
});
The jQuery on() can help you in this. First you need to detach appending DATA to your element ID like btn+btnNumber. You can add your custom information in any data-x attribute like data-custom-info and use the jQuery attr('data-custom-info') syntax to retrieve the information. The event handlers registered with on() method is also available for future elements(elements created after script execution). Like below.
When creating new button, add render it as..
<input .... class="btnWithData" data-custom-info="1" ... />
<input .... class="btnWithData" data-custom-info="2" ... />
and your event handler goes like..
$(document).ready(function(){
$('body').on('click','.btnWithData',function(){
//DO WHATEVER
var buttonData=$(this).attr('data-custom-info');
//DO WHATEVER
});
});
You should assign delegated event listeners using jQuery.on() method as #Ananthan-Unni suggests, but in the form:
$.on('click', 'button', listener)
In this case you do not need to assign unique ids or attributes. You can use tag name or class name as a selector (2nd argument).
Have a look here: https://api.jquery.com/on/ and read on delegated events.
Best is don't use closures they require memory. Rely on good old data tags, instead:
$(document).ready(function () {
$("#wrapper").on("click", "btnNameAttr", function () {
var n;
n = $(this).data("number");
// code goes here
});
});
To differentiate the actually clicked element inside #wrapper you use data-number attributes like this:
<div id="wrapper">
<img data-number="000" />
<img data-number="001" />
<img data-number="002" />
<img data-number="003" />
</div>
This code will perform much better and you can still have all functionality you want by using wrapping <div> elements and data-number="" attributes. And you don't interfere with class or id attributes you might already have on those elements.
You can even add the command to the tag:
<img data-number="000" data-command="edit" />
<img data-number="000" data-command="show" />
<img data-number="000" data-command="delete" />
And switch on it:
switch ($(this).data("command"))
{
case "edit":
// edit element with number n here
break;
}

Why this JS id does not work for multiple items

I got a 2 buttons and an image. When ever I press any of the buttons the image fades out. like this demo: http://jsfiddle.net/5wBuV/6/
the problem is that this is working only for the first button and the second one does not work. It might be a simple mistake but I am really beginning in JS.
$("#clickedButton").click( function() {
$("#hide").fadeOut("slow");
});
id of an element must be unique, if you use ID selector jQuery will return only the first element with the id.
In your case if you want to add same event handler to a set of elements, you can use a common class attribute and then use class-selector
<!-- The button -->
<a href="#" class = 'clickedButton'>
<img src="http://www.kwvs.pepperdine.edu/playbutton.png" />
</a>
<a href="#" class = 'clickedButton'>
<img src="http://www.kwvs.pepperdine.edu/playbutton.png" />
</a>
then
$(".clickedButton").click( function() {
$("#hide").fadeOut("slow");
});
Demo: Fiddle
Using id selector will only return zero/ one object.
If you want to refer to more than one object, use class selector. Like:
$('.clickedButton').click(function () {
$('#hide').fadeOut('slow');
});

Creating a "selected item" javascript code for navigation menu?

I have a navigation menu with about 10 items, and I put together this code to update the links for which is selected and which is not. It manually updates classes. The problem is, as you can probably tell, its inefficient and its a pain to update. Is there a better way of doing it?
$('#Button1').click(function(){
$('#Button1').addClass("selectedItem");
$('#Button2').removeClass("selectedItem");
$('#Button3').removeClass("selectedItem");
$('#Button4').removeClass("selectedItem");
$('#Button5').removeClass("selectedItem");
$('#Button6').removeClass("selectedItem");
$('#Button7').removeClass("selectedItem");
$('#Button8').removeClass("selectedItem");
$('#Button9').removeClass("selectedItem");
$('#Button10').removeClass("selectedItem");
});
You could try something like this -
$("[id^='Button']").removeClass("selectedItem");
$('#Button1').addClass("selectedItem");
This will first remove all the selectedItem classes from any element which has an id attribute starting with "button". The second command then adds the class to Button1
You could also simply bind all the elements with the same handler like this -
var $buttons = $("[id^='Button']");
$buttons.on('click', function ()
{
$buttons.removeClass("selectedItem");
$(this).addClass("selectedItem");
});
For each element, when clicked, the class will be removed - the element that was clicked with then have the class added.
Checkout the Attribute Starts With Selector [name^="value"] selector.
I would suggest using classes because this is exactly what they are for - to denote groups of elements. While you can easily select your buttons using the method proposed by Lix (and you should use this method if you can't modify HTML), using class is a more unobtrusive:
var $buttons = $('.button').on('click', function() {
$buttons.removeClass('selectedItem');
$(this).addClass('selectedItem');
});
Meta example: http://jsfiddle.net/88JR2/
You could have a class .button and apply it to all your buttons then
$('#Button1').click(function(){
$('.button').removeClass("selectedItem");
$('#Button1').addClass("selectedItem");
});

Categories