Fire click event for only one element with same class name - javascript

I have multiple div's with the same class name: ag-list-item
<!-- item one -->
<div class="ag-list-item">
</div>
<!-- item two -->
<div class="ag-list-item">
</div>
<!-- item three -->
<div class="ag-list-item">
</div>
They are dynamically created through an angular grid library I'm using, so I cannot set an ID attribute for any specific one.
I'm looking for a way to target only one specific div with the class name through a click event.
$('.ag-list-item').click() executes on all three elements; is there a way to only target one?
Update: 09/09/15
I found a solution that allows for specific index selection of a collection of div's with the same class, using the :eq() selector.
// select .ag-list-item at index 1
$('.ag-list-item:eq('1')').click();

As promised, I have done an update of my post.
$(document).ready(function () {
// If you want to select the first element :
$('.ag-list-item:first span span').click(function () {
// Your code
});
// If you want to select the second element, in this example
// Don't forget the quotes around the desired number
$('.ag-list-item:eq("1") span span').click(function () {
// Your code
});
// If you want the last element :
$('.ag-list-item:last span span').click(function () {
// Your code
});
)};
Please find the JSFIDDLE associated to this example (I have put some design style to a better understanding)

If you want a pure Javascript solution for speed, this could do the trick:
var els = document.getElementsByClassName('ag-visible-icons');
els[0].addEventListener('click', function() {
// Do something
});
For jQuery you could try:
$('.ag-visible-icons').first().click(function() {
// Do somehting
});
This is assuming the class you showed the the '.ag-list-item:first span span' path is the ag-visible-icon class

Related

CSS class added with .on('click') not visible after first event

I'm trying to apply a border to a dynamically generated element using $.on('click') and $.addClass(), but the class doesn't seem to be applied on the first click event. Otherwise, it works fine. What am I doing wrong?
$(document.body).on('click', '.card', function() {
var currentSelection = $(this)
var currentSelectionIndex = $(currentSelection).index()
$(currentSelection).addClass("selected")
if (currentSelectionIndex !== previousSelectionIndex) {
p = $("#searchResponse").children().get(previousSelectionIndex)
$(p).removeClass("selected")
}
previousSelectionIndex = currentSelectionIndex;
});
Solution: Assigning previousSelectionIndex a value a the beginning of my script and it fixed the issue.
I'm not entirely clear on your question given the information provided.
However, if I understand the problem correctly you have a container element with the id="searchResponse" that has many children each with the class="card" and you're essentially trying to add class="selected" to a particular card when it is clicked ensuring that only one card at a time can be 'selected'. If this is the case..
Select only one card at a time:
$('#searchResponse').on('click', '.card', function(){
$('.card.selected').removeClass('selected');
$(this).toggleClass('selected');
});
If you need to select and unselect multiple then try this:
$('#searchResponse').on('click', '.card', function(){
$(this).toggleClass('selected';)
});
Working Codepen

jquery - css does not work after .after()

In my html code i change the background color of all elements with the id '#mutable', with a click on button 'blue' or 'red'.
With the third button 'load' i .append() a new HTML with the same id.
But the background color does not change for the new elements?
Whats going wrong?
fiddle
html
<div id="mutable" style="width:50px;height:50px;" class="blue">sjdfhksfh</div>
<div id="newHTML">newHTML</div>
js
$(document).ready(function() {
$('#blue').on('click', function() {
$('#mutable').trigger('blue');
});
$('#red').on('click', function() {
$('#mutable').trigger('red');
});
$('#load').live('click', function(event) {
event.preventDefault();
$('#newHTML').after('<div id=\"mutable\" style=\"width:50px;height:50px;\">...</div>');
event.stopPropagation();
});
$('#mutable').bind('red', function(e) {
$('#mutable').addClass('red').removeClass('blue');
});
$('#mutable').bind('blue', function(e) {
$('#mutable').addClass('blue').removeClass('red');
});
});
You are always creating a new div with the id #mutable. Now jQuery in terms of an ID just runs down the DOM and when it finds the first occurance of your ID, it changes it, but nothing else.
For some solutions, you could use a class .mutable instead of an id - but then every created div would be changed on click.
Or you could enumerate your IDs with a number like #mutable1, #mutable2 and so on and change your menu to select the specific div.
Or, to change just the last occurance of your dynamically created divs, use the :last - CSS- Pseudoclass.
1) id should be unique at page. And selectors like #mutable match only first element with such id -- So after pressing 'load' you create new element with the same id, but $ still match old one
2) try next ( I just change your id-selector into attr-selector which allow find all elements with id ):
$('#mutable').bind('blue', function(e) {
//alert('blue');
$('[id=mutable]:last').addClass('blue').removeClass('red');
});
http://jsfiddle.net/q3wzwr6z/

Using jQuery to toggle specific classes [misleading?]

I have three article tags that each have 1 section which I need to animate to appear i.e height from 0px to whatever px. Each article has an ID what is the most efficient way to have an on click event for each one without writing a separate function for each individual id i.e is there a 'get clicked article's id' type method?
Thanks
This is what I would do,
jQuery:
$('.art h1').on('click', function() {
$(this).parent().find('p').stop(true).slideToggle();
});
html:
<div class="art">
<h1>Some article stuff</h1>
<p>text goes here</p>
</div>
fiddle: JSFIDDLE
If you want it to slide up and have only one open at a time then you can make a minor edit like so,
jQuery:
$('.art h1').on('click', function() {
$('.art p').slideUp();
$(this).parent().find('p').stop(true).slideToggle();
});
fiddle: Only one active JSFIDDLE
You can combine multiple selectors with a comma:
$('#id1,#id2,#id3').click(function() {
$(this).animate(...);
});
...or you could add class="something" to each element and just select that:
$('.something').click(function() { ... });
Use a class for the click event, instead of ids .. you can then use the id or some other attribute to identify which article to expand.
$('.someClass').click(function() {
thisId = $(this).attr('id');
$('#whereTheSectionsAre').find('.active').removeClass('active').next().slideUp(400);
$(thisId+'article').toggleClass('active').next().slideDown(400);
return false;
});
You can check some examples here, mainly if the id's are dynamic:
http://jsbin.com/uzEkiQa/3/
The first approach is the one already suggested, but with dynamic id's:
$('div[id^="id_"]').text("Changed by regexep");
The second one if your matching is a bit more hardcore uses filter:
var reg = new RegExp(/id_\d+/);
$('div[id^="id_"]')
.filter(function(index, item) {
return reg.test(item.id);
})
.text("Changed by filter and regexp");
After the selection you can apply the behaviours you want. Check the JSBin to play around.

jQuery click function using same classes

I have a dropdown function that I need to work only on the div clicked, not all (I have 14+ of the same classes on the page that need to be displayed when a certain one is clicked)
At the moment my jQuery is as follows.
$('.qacollapsed').hide();
$('.qa').click(function () {
$('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});
Of course, that is toggling all qacollapsed classes when there is 14 on the page (Q&A)
Is there a way for it to only drop down the one that is clicked?
the HTML
<div class="qa">
<h4 class="question"> </h4>
</div>
<div class="qacollapsed">
<p> </p>
</div>
It would be helpful to provide a snippet of HTML here, but I'll take a guess at the structure of your markup for now..
Instead of referencing all .qacollapsed elements, you need find elements that are close to the .qa that was clicked, e.g.:
$('.qa').click(function () {
$(this) // start with the clicked element
.find('.qacollapsed') // find child .qacollapsed elements only
.slideToggle();
$(this).toggleClass('active');
});
This will work if .qacollapsed is inside .qa - if not, you might need to use next (for siblings), or one of the other jQuery tree traversal methods.
Yo could find() it or use this as a context in the selector to choose only a descendent of the clicked object
$('.qa').click(function () {
$('.qacollapsed', this).slideToggle();
//You could do $(this).find('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});
Check out the jQuery selectors and why not just use $(this)?
$('.qacollapsed').hide();
$('.qa').click(function () {
$(this).toggleClass('active').next().slideToggle();
});
Personally, I'd give all the divs IDs, the clickable bit being the ID of the question in the database for example, and the answer just being id='ID_answer' or something, then use jquery to slide in the div with the id corresponding to the link clicked, ie
Var showIt = $(this).attr('id') + '_answer'
$('.qacollapsed').not('#'+showIt).hide();
$('#'+showIt).slideToggle;
That will hide all the divs without that ID and show the required one.
Dexter's use of .next above looks simpler though, I've not tried that as being relatively new to jquery too.

jquery .each() loop

i want to read all links in ".vm-video-title"-divs and post them each in the same div. So i made this script:
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("div.vm-video-title>a").text());//add to div the link
});
but i have the problem that it reads ALL the links of all divs and put them in one div.
example:
<div class="vm-video-title">Text1</div>
<div class="vm-video-title">Text2</div>
<div class="vm-video-title">Text3</div>
output:
Text1Text1Text2Text3
Text2Text1Text2Text3
Text3Text1Text2Text3
wanted output:
Text1Text1
Text2Text2
Text3Text3
You can select the <a> elements directly, and use the after()[docs] method to append the content of each after each one respectively.
$("div.vm-video-title > a").after(function() { return $(this).text(); });
This doesn't do a "destroy then recreate" of the existing elements like the html()[docs] method will.
Working example: http://jsfiddle.net/CCr9C/
This should do the job for you,
you need to find the div inside current element in the loop (el).
$('.vm-video-title').each(function(i, el) {
el = $(el);
el.html(el.html()+el.find("a").text());
});
in your code you are adding text() of all matching "a" tags in your divs (i.e. Text1Text2Text3)
You were almost there. Instead of : $("div.vm-video-title").text(), which gives you text inside any div with class vm-video-title, you need to find a tag inside current div and get text from it. We pass this as context for selecting a inside current div jQuery( selector, [context] )
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("a", this).text());
});

Categories

Resources