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

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

Related

Fire click event for only one element with same class name

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

How to change/remove the siblings method

I grabbed this code when I was searching other questions, but when I tried to fit it to my needs I hit a problem. As my links are spread across two parent divs, it doesn't interact correctly with the other siblings.
var make_button_active = function () {
//Get item siblings
var siblings = ($(this).siblings());
//Remove active class on all buttons
siblings.each(function (index) {
$(this).removeClass('active');
});
//Add the clicked button class
$(this).addClass('active');
}
$(document).ready(function () {
$(".clicked").click(make_button_active);
});
Here is the Fiddle
If you click Link 1 and then click Link 6 for example, Link 1 stays highlighted when Link 6 highlights also.
Link 1-3 interact with each other and 4-6 do as well, but separately. How cna I get them to all talk to each other and highlight on/off?
Updated your Fiddle. Initially, you were only selecting the siblings (implies all under one parent). But you need to select across parents and hence siblings would not work. Instead you have to use a generic identifier - .clicked in this case.
Just change the following line:
var siblings = ($(this).siblings());
to:
var siblings = $('.clicked');

JQuery Handling events when elements are being generated at run time

Disclaimer: I'm new to JQuery
I don't know how to title this question but first my code is below
$(document).on("click" ,'[id^="picChangeAddress"]', function() {
$('div[id^="divAddressSet"]').toggle();
});
Please not that I have the same numbers of div's and checkboexes, each name format is same also such as checkboxes picChangeAddress1, picChangeAddress2 and so on, and div's divAddressSet1, divAddressSet2 and so on.
I've used the above code because these id's are being generated at run time. There are few things i need to ask first when i click on one checkbox all it effects every div div[id^="divAddressSet"] on the page and they all toggled when i click on any any of [id^="picChangeAddress"] checkbox. I would like you to help me on how to only show or hide only one div at a time.
Any Idea?
You can extract number from ID, then you can use ID selector to hide the div
$(document).on("click" ,'[id^="picChangeAddress"]', function() {
var num = parseInt(this.id.match(/\d+/)[0],10); //Extract number
$('#divAddressSet'+num).toggle();
});
You need to extract the number from the ID and use that so that you target the correct selector:
$(document).on("click" ,'[id^="picChangeAddress"]', function() {
$('div[id="divAddressSet'+this.id.substring(16)+'"]').toggle();
});
Try this:
$(document).on("click" ,'[id^="picChangeAddress"]', function() {
var o = this.id.split('').pop();
$("#divAddressSet"+o).toggle();
});

Adding onclick events to appended div tags in JavaScript

I am trying to add a click event to a bunch of div elements that I created by appending them and I am having some trouble.
I have a bunch of div elements the with the ids a0 ---> an. I am trying to create a for loop after the divs are created to assign them click events. The issue is the way I am doing it when the click event happens I do not have any way to track which div fired the event. The code bellow might make that more clear. So the issue I am having is that #a + i always returns the last div, and I want it to return the div number that was clicked.
$(document).ready(function () {
traverse(oo);
for (i = 0; i <= groupNum; i += 1) {
$("#a" + i).click(function () {
console.log("#a" + i + "clicked");
});
}
});
I thought about returning a closeur, but that seems I would make it even more complicated. Does anybody have any advice on how to do this the best?
Thanks in advance.
I'm not sure what you are trying to do but if you just want to assign a click event to a bunch of elements then use the correct selector (note the use of $(this) to get the clicked element):
$("div").click(function(){
var clickedDiv = $(this);
var id = clickedDiv.attr("id");
});
If you don't want ALL div elements, then you could add a class to them and use a different selector:
$(".MyDivClass").click(function(){...
or without the class, a 'starts with' on the id (the following with get all div elements where the id attribute starts with "a"):
$("div[id^='a']").click(function(){...
If you are dynamically adding divs with other javascript and you want them to automatically have the click events, use the on function...
$(document).on("click", ".MyDivClass", function(){...
The variable i will, as you noticed, will contains the value set on the last iteration. Change
console.log("#a" + i + "clicked");
by
console.log(this.id + " clicked");
Within the event handler, this is the target DOM element for the event.
You can do it in this way:
$('[id^="a"]').click(function () {
console.log(this.id+" clicked");
});
You may assign a click event to a class instead of to specific ID's and use conditional statements within the click function to do different things base on ID.
$(documnet).ready(function(){
$('.clickclass').click(function(){
/* conditional code here */
});
});

Deleting <li> issue

I'm building a recipe saving application where I have a form that looks like this http://jsfiddle.net/LHPbh/.
As you can see, I have a set of form elements contained in an <li>. You can click Add Ingredient and have more li's added to the field.
My problem is:
The first li is the only one that deletes. If you click Add Ingredient, and then try and delete that one, nothing works?
Is there a way to not have the first li have a delete by it, but all subsequent li's have a delete link on the side? (Just because there should always be at least one ingredient?)
When you call clone(), it isn't duplicating the events. You need to call clone(true) in order for it to do this, as explained in the documentation.
You did not put an event listener on the cloned elements. Also, you should not give the "delete"-link its own id, as those need to be unique.
To make the first ingredient have no delete button, just don't include one in your markup but only dynamically create and append them to the cloned elements:
var deleteButton = $("<a class='float-left'>Delete</a>").click(deleteThis);
$('ul#listadd > li:first')
.clone()
.attr('name', 'ingredient' + newNum)
.append(deleteButton)
.appendTo('ul#listadd');
function deleteThis() {
var li = $(this).closest('li')
li.fadeOut('slow', function() { li.remove(); });
}
Demo at jsfiddle.net
http://jsfiddle.net/LHPbh/2/
$('.deleteThis').live("click", function () {
var li = $(this).closest('li')
li.fadeOut('slow', function() { li.remove(); });
});
It is answer to the 1. point. The problem was, that the eventhandler binding did not happen in newly created elements, because this code runs only on the load of the page. This can be solved by using .live(). And an other problem was, that id-s must be unique. So instead id, here you can use class .deleteThis.
http://jsfiddle.net/LHPbh/19/
This has added answer to the 2. point:
if ($("#listadd li").length == 1) {
return;
}
If the list only contains 1 li element the rest of the callback will not run.
You are adding items that are added to the DOM dynamically, thus jQuery can't access them :)
In this case you can use the following code:
$(document).on('click', '.selector', function(e) {
//code here
});
Secondly, you were loading a quite old version of jQuery.
Thirdly, you were trying to select an element with an ID that already existed, and ID's can only exist one time. I've changed it to a class in the updated example.
Lastly, you were defining the class of the link twice like this:
<a class='float-left' id="deletethis" href='#' class="deletethis">Delete</a>
That also gave a problem, so I changed it to correct markup like this:
<a class='float-left deletethis' href='#'>Delete</a>
Good luck :) I've updated your jsFiddle here:
http://jsfiddle.net/q4pf6/

Categories

Resources