jquery addClass() to enable a button as a link [duplicate] - javascript

This question already has answers here:
jQuery click() still being triggered after .clickable class is removed
(7 answers)
Closed 7 years ago.
On page load, I have a class attached to a bootstrap <button> called .link-active that I use to make the <button> act like a link with this script:
$('.link-active').click(function(){
window.location='foo.php';
});
However, when I successfully remove the .link-active class using removeClass(), the button continues to act like a link when clicked and takes me to foo.php even when the class isn't on there. Any ideas as to what I am doing wrong?

Prior to removing the class you should also remove the event:
$('.link-active').off('click');
Or use chaining:
$('.link-active').off('click').removeClass('link-active');
The reason it continues to work is because the attached event already has a reference to the element its attached to. It doesn't query the DOM every time. If you don't want to remove the event you could use event delegation to attach the event and then it would work the way you imagine.
$('body').on('click', '.link-active', someFunction);

Related

Clicking a <span> tag to run JQuery javascript function [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I create a span using PHP like this.
if ($subnetkey == 1 ) { echo ("<span class='subnetkey'>S/N of: $subnetnum</span> ");}
It works, and shows the correct data on screen. Additionally if I look at it using 'Inspect Element' its properly formatted.
<span class="subnetkey">S/N of: 780</span>
I have this script at the top of the page. I've also tried it at the bottom.
<script>
$(document).ready(function(){
$(".subnetkey").click(function() {
alert("subnet click mode");
});
});
</script>
When I click the span, nothing happens. I get no errors, and of course I don't see the alert fire.
It seems like this is a timing issue between building the page dynamically and using the page. But in case thats not it, what can I do to make the function fire?
JQuery Event Methods like click(), dblclick(), mouseenter() etc. work only for elements already created when DOM is rendered. For dynamically created elements you use on() method with the below syntax (see previous post):
$(staticAncestors).on(eventName, dynamicChild, function() {});
Since it is a dynamically created element your code won't work. Try:
$(document).on('click', '.subnetkey', function() {
alert("subnet click mode");
});
jQuery is only aware of the elements in the page at the time it runs, so new elements added to the DOM are unrecognized by jQuery. To combat the problem use event delegation, bubbling events from newly added items up to a point in the DOM which was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go all the way up the DOM tree. Ideally you should delegate to the nearest parent existing at the time of page load.

javascript, jQuery: How to re-listen for click events [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I am listening for click events on the class notification-link:
$(document).ready(function(){
$('.notifications-link').click(
function(){
$('.notifications-popup').addClass('show')
}
)
});
Works fine. The problem is, if I append a new Element with the class notification-link to the DOM, jQuery doesn't listen for it = if you clicked on the appended Element, nothing happens.
How can I fix that?
instead of
$('.notifications-link').click(function(){...})
use
$(document).on("click", ".notifications-link", function(){...});
this way you're attaching the event to the document and then checking to see if the click landed on ".notifications-link" and will work will all newly added ".notifications-link"'s
You need to use event delegation for the events to work on the elements added via JS.
$(document).ready(function () {
$('body').on('click', '.notifications-link', function (e) {
$('.notifications-popup').addClass('show');
});
});
For detailed explanation about how Jquery event method like on, click etc works please check this post:
http://elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/

.click not being registered on button [duplicate]

This question already has answers here:
jQuery click event not working after adding class
(7 answers)
Closed 7 years ago.
I have this button rendered after some text in an unordered list:
The button's HTML is like this:
<a
data-action="remove"
data-class-name="ECEC 301 Advanced Programming for Engineers Lab"
class="btn btn-danger remove-item btn-xs btn-font-12-px btn-raised margin-add-to-cart mdi-content-remove-circle-outline">
</a>
And this is the unordered list element it is within:
I am trying to write some jQuery that calls an action when the button is clicked, but no matter what I write, I just cannot register the click action, for example:
$('.btn.btn-danger.remove-item').on('click', function(){
console.log("you should see this");
});
$("[data-action]").click(function() {
console.log("yeah");
});
$('a[data-action="remove"]').click(function() {
console.log("yeah");
});
EDIT: The button is created dynamically AFTER page-load using jQuery (I call my JSON API to create the unordered list of classes)
Since button is generated dynamically you need to use event delegation
$(document).on('click','.btn.btn-danger.remove-item', function(){
console.log("you should see this");
});
Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future.
Taken from : http://learn.jquery.com/events/event-delegation/
The issue is that the element doesn't exist when the click handler is being added.
Basically, you are saying "hey jquery, find this element and do XYZ when it is clicked". jQuery looks for it, doesn't find anything (since the element has not been created yet), and since it is chill it doesn't say anything to you about it (it would be super annoying if it errored out all of the time).
The way around this is by using event delegation. What that means is that you attach the event to an element that will be there, and then jQuery filters every event sent to that parent element and checks to see if the event that triggered it happened to an element that matches the selector.
It may sound complicated, but it is straight forward. All you need to do is update
$(".btn.btn-danger.remove-item").on("click...
to this
$(document).on("click", ".btn.btn-danger.remove-item"...

jQuery Click Function not Working on Class [duplicate]

This question already has answers here:
Events triggered by dynamically generated element are not captured by event handler
(5 answers)
Closed 8 years ago.
So I have a bunch of game pieces that I want to be clickable. If I add a click function to a button I get the desired result, but when I add it to the game piece class, it fails to work.
Here is an example that works fine on jsfiddle, but not when I use it in my script:
http://jsfiddle.net/sLt7C/
Here is what I want to do on my page:
$('.gamePiece').click(function(){
$('.gamePiece').addClass("toggled");
});
This doesn't work, but if I switch the identifier to a button on the page it does work:
$('#btn_AddClass').click(function(){
$('.gamePiece').addClass("toggled");
});
What could be causing this to fail?
Not sure if this has any impact on what could be causing it to fail, but the "game pieces" are span elements that are generated after clicking a "New Game" button.
Here is a fiddle showing more code http://jsfiddle.net/sLt7C/4/
For further clarification:
This doesnt work
$('.gamePeice').click(function(){
$(this).addClass("toggled");
});
This works
$('#btn_addClass').click(function(){
$('.gamePeice').addClass("toggled");
});
If the game pieces are added after the page load (i.e. by clicking a button) you need to use event delegation by using jquery .on()
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$(myContainer).on('click', '.gamePiece', function(){
$(this).addClass("toggled");
});
I think you want this:
$(document).ready(function() {
$(document).on('click', '.gamePeice', function(){
$(this).addClass("toggled");
});
});
instead of
$('.gamePeice').click(function(){
$(this).addClass("toggled");
});
$('#btn_addClass').click(function(){
$('.gamePeice').addClass("toggled");
});
just prove http://jsfiddle.net/aras7/sLt7C/7/

Visit link when triggering click [duplicate]

This question already has answers here:
jQuery find events handlers registered with an object
(16 answers)
jQuery 1.8 find event handlers
(2 answers)
Closed 8 years ago.
I have some links that have events bound to them and some links that do not.
These links are having their click event triggered by a change in a select box.
See this fiddle
Is there a way for jquery to visit a link if there is no event bound that link?
I do not want to reference the url within the select box vlaue attribute, I want to reference the url in the anchor tag.
something like (pseudo code) -
if (link.hasEventHandler('click')){
trigger click
} else {
window.location = link.attr('href')
}
EDIT - There's a plugin that does exactley what I need to do here - https://github.com/sebastien-p/jquery.hasEventListener
File size is an issue, so I'd like to avoid using it.
I'm using the latest jquery so cannot use .data('events')
As far as I am aware you can't 'fake click' in JS. The click event trigger simply triggers the onClick JS event, and does not simulate clicking on a link in the browser, entirely. However, all you need to do is grab the href and redirect to that page using JS. I updated your fiddle with a couple of lines that do this.
http://jsfiddle.net/9j8QS/1/
$('a:not(.event-bound)').click(function(event) {
window.location.href = $(this).attr('href');
});
The selector selects all anchor tags that don't have the class event_bound.
You could implement something the Dropdown button from Twitter Bootstrap (http://twitter.github.com/bootstrap/components.html#buttonDropdowns). Bootstrap also allows you to customize your download. When you select only dropdown, it comes out to ~40kb. It doesn't even require jQuery because it's all CSS.
Looking at your code, you have to select the link with the href attribute which is same with the selected value in your combobox. Something like:
$('#nav').on('change', function(event) {
var targetHref = $(this).find("option:selected").val();
$('a[href="'+targetHref+'"]').each(function() {
$(this).trigger('click');
});
});
Assuming you have a click event for your links. If not, just give your links the same class and write a click event for that class to set the window location to the href attribute of the object.

Categories

Resources