A way to check if any element of class is clicked - javascript

Is there a way to check if any of the elements of a class have been clicked with jQuery? I want to detect if an element with a certain class has been clicked.

I want to detect if an element with a certain class has been clicked.
Well you could always subscribe to the .click() event handler which will be invoked when a DOM element is being clicked upon:
$('.someClass').click(function() {
// here you could use "this" to get the DOM element that was clicked.
});
you could then associate some metadata information with this DOM element if you want to track it using the .data() function:
$('.someClass').click(function() {
var isClicked = $(this).data('clicked');
if (!isClicked) {
// it's the first time we are clicking on this element
$(this).data('clicked', true);
} else {
// the user has already clicked on this element
}
});

Related

Add querySelectorAll to add a class to a button

I'm having difficulty with using Javascript to add a class to a button.
Context: I have multiple cards in an instragram type format with a post and a "like" button. I want to add a class of card__like-button which changes the image to a filled heart but i remembered that querySelector only applies to the first element, instead i tried using querySelectorAll but now the code doesn't apply to anything.
First attemp:
// Controls for active like button
let likeButton = document.querySelector(".card__like-button");
// Event listener for like button click
likeButton.addEventListener("click", likeButtonClick);
// Add class on button click
function likeButtonClick() {
likeButton.classList.toggle("card__like-button_active");
}
Second attemp
// Controls for active like button
let likeButton = document.querySelectorAll(".card__like-button");
// Event listener for like button click
likeButton.addEventListener("click", likeButtonClick);
// Add class on button click
function likeButtonClick() {
likeButton.classList.toggle("card__like-button_active");
}
I created the following codepen to replicate the problem.
I've search on the site, w3schools documentation, etc. and can't seem to find what am I doing wrong.
Because of the document.querySelectorAll method will return an array of NodeList details see here, you cannot directly assign the addEventListener event to a list.
Instead, you have to loop through each element and assign events to it
document.querySelectorAll(".card__like-button").forEach(ele => {
ele.addEventListener("click", likeButtonClick);
});
// Add class on button click
function likeButtonClick() {
this.classList.toggle("card__like-button_active");
}
Try it :
let likeButtons = document.querySelectorAll(".card__like-button");
Array.from(likeButtons).forEach(ele => {
ele.addEventListener("click", likeButtonClick);
});
// Add class on button click
function likeButtonClick() {
this.classList.toggle("card__like-button_active");
}

Jquery how to trigger click on an element that gains focus

I am working with caph framework and i trying to click in every id focused
$(event.currentTarget).on('selected',function() {
var value = $(this).prop('id');
$('#' + $(this).prop('id')).trigger('click');
});
You can access the event target with $(this) in jQuery. To automatically click on the selected element you could do
$(event.currentTarget).on('select', function() {
$(this).click()
// or $(this).trigger('click')
};
If I understand your question right though you're asking how to click every element with a given ID - please note that you should be using classes for this, as IDs are supposed to be unique. You could achieve that with the following:
$(event.currentTarget).on('select', function() {
$('.yourClassName').click()
};
This will click on every element with the given class.

Why is my delegated event handler not working?

I have a button with id of Strike but the JQUERY event doesn't seem to work? This event here worked previously, but ONLY if the button existed when the DOM loaded.
dom.el('Strike').onclick = strikeSkill;
Now I have my buttons dynamically generated, so the "Strike" button is generated later. So the previous code above no longer works, because Strike = Null.
I am using the Jquery .on function, filled up my arguments, but now when I click the strike button, nothing happens. No attacking. Why is this?
function strikeSkill() {
activeCheck();
if (upgradeActive == true){
radialSelector(strike);
}
if (upgradeActive == false){
HitCalc(player.cc, monster.cc);
actor.expCounter(player.cc);
actor.balanceCounter(player.cc, monster.cc);
}
};
$('#Strike').on('click', '#Strike', function() {
strikeSkill();
});
Your current event handler is looking for a #Strike element within #Strike, which is incorrect (not to mention would be invalid HTML).
You can fix this by using a static parent element for the primary selector:
$(document).on('click', '#Strike', function(){
strikeSkill();
});
In the example I used the document, however for best performance it should be the nearest static parent element to #Strike which is available when the DOM loads.

Navigate immediately to first <p:menuitem> when <p:submenu> itself is clicked

I have a dynamic <p:menubar> as follows.
<p:menubar style="position: relative; height: 30px; visibility: visible;">
<p:submenu label="Category" icon="ui-icon-document" styleClass="mainMenu">
<c:forEach var="row" items="#{parentMenuManagedBean.category}">
<p:submenu label="#{row.catName}" icon="ui-icon-contact" styleClass="subMenu">
<c:forEach var="subRow" items="#{row.subCategoryList}">
<p:menuitem value="#{subRow.subCatName}" url="ProductDetails.jsf?subCatId=#{subRow.subCatId}"/>
</c:forEach>
</p:submenu>
</c:forEach>
</p:submenu>
</p:menubar>
</p:submenu>s inside </p:menubar> are not clickable.
There are CSS classes which are bound to JavaScript functions. When these <p:submenu> are clicked, the following functions are called.
$(function(){
$(".mainMenu").bind("click", function(){ alert("mainMenu was clicked"); });
});
$(function(){
$(".subMenu").bind("click", function(){ alert("subMenu was clicked"); });
});
But when clicking on the inner most <p:submenu> both of these functions are called that should not happen.
Also how to uniquely identify each <p:submenu>, when they are clicked?
Is there a way to pass some value so that they can uniquely be identified like query-string appended to a URL?
But when clicking on the inner most <p:submenu> both of these functions are called that should not happen.
You're victim of event bubbling. In all browsers, when a DOM element receives an event, this is after processing on the current element propagated to all of its parents. All of their event listeners, if any, are also invoked, unless you return false from the current listener function, or explicitly stop the propagation by calling event.stopPropagation() and return from the function as usual. The difference with return false is that the default action of the click event on the current element (going to the given URL) will still be performed.
Also how to uniquely identify each <p:submenu>, when they are clicked?
The DOM element responsible for firing the event is in the listener available by this. You can wrap this further into a jQuery object by simply constructing it with $(). In case of <p:submenu>, that'll be a HTML <li> element which in turn has an <a> element as child.
Is there a way to pass some value so that they can uniquely be identified like query-string appended to a URL?
Usually, you'd better explore the DOM element itself. For example, by checking the text content of the child <a> element.
All in all, here's a rewrite, note that the event object is available as 1st function argument:
$(document).on("click", ".mainMenu", function() {
console.log("mainMenu was clicked");
});
$(document).on("click", ".subMenu", function(event) {
event.stopPropagation(); // Stop event bubbling.
var $this = $(this); // That's the <li> element.
var $link = $this.children("a"); // That's the immediate child <a> element.
var label = $link.text(); // You could use it to identify the submenu.
// ...
console.log("subMenu with label " + label + " was clicked");
});
(note that I also replaced the $(function(){}) and $.bind() by $(document).on(), this makes it safe against DOM updates on ajax requests; you don't need to re-execute the whole script then)
Update: as per the comments, the concrete functional requirement, which wasn't clear from the initial question at all (I've improved the question title now), is to navigate to the same URL as menu's first item when the submenu itself is clicked. In that case, you'd better hook on the submenu's own <a> element directly by the .subMenu>a selector and perform a window.location on the URL of the menu's first <a> element. Here's another rewrite:
$(document).on("click", ".subMenu>a", function() {
var $this = $(this); // That's the submenu's <a> element itself.
var $link = $this.next().find("a:first"); // That's menu's first <a> element.
var url = $link.attr("href"); // The URL of that link.
// ...
window.location = url; // It'll change the document immediately. No need to stop propagation.
});
you need to use stopPropagation
$( ".subMenu").click(function( event ) {
event.stopPropagation();
// Do something
});
This will stop the parent to be notified of the event.
Check this http://api.jquery.com/event.stoppropagation/

.class selector not working

I'm working in a card game system that the player can select the card by clicking on it and then select the place to put it on. My problem is that when the player click on the target place, nothing happens.
This is my try: http://jsfiddle.net/5qMHz/
And this is my code:
function target() {
$(".target").on("click", function() {
$("#"+x).appendTo(this);
console.log(x);
});
};
What's wrong?
Try binding with document, since you change the class during document ready and there was no element with the class target initially
$(document).on("click",".target", function() {
$("#" + x).appendTo(this);
console.log(x);
}
WORKING FIDDLE
Firstly, your practice of putting function references in to jQuery objects is rather odd. The problem however is that because the .target class is applied after DOM load you need to use a delegate selector. Try this:
var $card
$(".card").on("click", function () {
$card = $(this);
if ($(".myslot").length) {
if ($(".myslot").is(':empty')) {
$(".myslot:empty").addClass("target");
} else {
alert('No empty slots');
}
}
});
$('.field').on('click', ".target", function () {
$card.appendTo(this);
$card = $();
});
Example fiddle
At the moment you are trying to bind the event handler, the elements don't have a class target yet. From the documentation:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().
(Technically the elements exist, but they are not (yet) addressable by the class target)
You have three options to solve this:
Add the class to your HTML markup.
Bind the handler after you added the class to the elements.
Use event delegation.
The first two don't really fit to your use case, since your are adding the class target in response to an other event and the number of elements with the class target changes over time. This is a good use case for event delegation though:
$('.field').on('click', '.target', function() {
// ...
});

Categories

Resources