Jquery addClass for an added class [duplicate] - javascript

Tough to come up with the title for this question.
More for proof of concept, I'm wondering why this doesn't work. What I'm attempting to do is use a jquery event to change the ID attribute, then use another jquery event bound to this newly changed ID.
For example:
<?php
echo <<<END
<html>
<head>
<style>
#before {
color:maroon;
}
#after {
color:blue;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<title>Test</title>
<script type="text/javascript">
$(document).ready(function(){
$("#before").hover(function() {
$(this).attr("id","after");
});
$( "#after" ).click(function() {
alert( "Handler for .click() called." );
});
});
</script>
</head>
<body>
<p id="before">TEST TEXT</p>
</body>
</html>
END;
?>
On hover over my test text, the color changes from maroon to blue, as expected. It is my understanding that the text would now have an ID of "after" and the click event handler function would apply when clicked. However that is not the case the quick event handler and its associated alert does not appear to trigger.
I am new to jquery is there perhaps an update handlers function I'm overlooking?

It works with the same principle as Event binding on dynamically created elements?.
When you add a event handler to an element where the element is found using a selector, the selector is executed only once when the code is executed after that the handler is added to the element. Once is has happend if you change the selector values associated with the element it will not reflect in the attached handlers.
For example in your case you are adding the a handler to the element with id before in dom ready handler, so once the dom ready event is fired your selector is evaluated and it returns a single element to which you are adding the handler. In the same dom ready handler you are trying to add a click handler to an element with id after, but at dom ready there are no elements with that id so that handler is not attached to any element.
Now at a later time you are changing the id of the elemnet, but it will not affect in the already attached handler nor will it add a new handler.
The solution here is to use a mechanism known as event delegation.
Demo:
$(document).ready(function() {
//there is no need to use hover as your want to add the class when the mouse enter the element and you don't want to do anything in mouseleave
$("#mytarget").mouseenter(function() {
$(this).addClass("after").removeClass('before');
});
//look at the use of event delegation
$(document).on('click', '.after', function() {
alert("Handler for .click() called.");
})
});
.before {
color: maroon;
}
.after {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="mytarget" class="before">TEST TEXT</p>

You can fire the click event after the hover event
$(document).ready(function(){
$("#before").hover(function() {
$(this).attr("id","after");
$( "#after" ).click(function() {
alert( "Handler for .click() called." );
});
return false;
});
});

Related

Use one() in inline onclick attribute

I have a function that is triggered on an inline onclick.
What I want is for that function to get called only once but don't know how to do that with an inline onclick. It's working at the moment but runs everytime the user clicks rather than just once.
This is how I have it:
HTML
<div class= "container" onclick="modal('#modal')"></div>
I have tried having it as a Jquery function as follows and remove the above click but that is not working either:
$(".container").on( "click", modal( '#modal') {
alert( "The event happened!" );
});
Any idea how to make it so the function only runs once?
Thank you
If you wish to use jQuery's one(), you'll need to remove the onclick from the HTML, and change the JS to read:
$( ".container" ).one( "click", function() {
alert( "The event happened!" );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class= "container">Container</div>
This way, the alert() will only show on the first click.
If you wish to use the on() as stated in your question, use $(this).off('click'); to remove the event listener after the fist press:
$( ".container" ).on( "click", function() {
alert( "The event happened!" );
$(this).off('click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class= "container">Container</div>

Could not catch the click event for a class which is appended by js

I appended the checkbox input field from javascript. after that, I need to catch click event of that checkbox field. But I could not. I tried with these following instruction:
- An append in jquery code and click function?
- jQuery 1.9 .live() is not a function.
This is my code
var htmlData='<input type="checkbox" name="is_pay[]" class="is_pay">';
$('.container').append(htmlData);
$('.is_pay').on('click', function(){
alert('hi');
});
Because that item does not exist when the script is run, so listen for a click on .container:
var htmlData='<input type="checkbox" name="is_pay[]" class="is_pay">';
$('.container').append(htmlData);
$(".container").on("click", ".is_pay", function() {
alert("hi");
});
Event handler will only run if element exist on the page therefore your script click handler is not worked as you are adding checkbox dynamically .
If any new element injected to page dynamically then use delegated event to attach event handler . Replace click handler with the following code
$("document").on("click", ".is_pay", function() {
alert("hi");
});
You can simply handle with .click()
var htmlData='<input type="checkbox" name="is_pay[]" class="is_pay">';
$('.container').append(htmlData);
$('.is_pay').click(function(event) {
alert('hi');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='container'></div>

jquery DOM mutation

I have made this:
<span class="a">test 1</span><div></div>
Why .b does not activate the alert?
$( ".a" ).click(function() {
$('div').html('<span class="b">test 2</span>');
});
$( ".b" ).click(function() {
alert("Hello");
});
I do not understand how to detect the mutation of the DOM.
since .b is created after the query was done. when you call $(".b") in your script nothing is found, and the click event is not attached to it. You can solve it by attaching the event to the document like so:
$(document).on("click", ".b", function () {
alert("hello");
});
The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on().
$('div').on("click", ".b", function () {
alert("hello");
});
The selector runs on execution, meaning that .b was already searched for when the page loaded, rather than after you added the dom.
To demonstrate how selectors run in line, the code works if you define it right after appending the element:
$( ".a" ).click(function() {
$('div').html('<span class="b">test 2</span>');
$( ".b" ).click(function() {
alert("Hello");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="a">test 1</span><div></div>
However, the correct way of doing this would be to define a parent-based selector. The following is setting a click event to the parent that filters the target for the .b selector.
$( ".a" ).click(function() {
$('div').html('<span class="b">test 2</span>');
});
$(document.body).on("click", ".b", function () {
alert("Hello");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="a">test 1</span><div></div>

jQuery click function not working with added class [duplicate]

Tough to come up with the title for this question.
More for proof of concept, I'm wondering why this doesn't work. What I'm attempting to do is use a jquery event to change the ID attribute, then use another jquery event bound to this newly changed ID.
For example:
<?php
echo <<<END
<html>
<head>
<style>
#before {
color:maroon;
}
#after {
color:blue;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<title>Test</title>
<script type="text/javascript">
$(document).ready(function(){
$("#before").hover(function() {
$(this).attr("id","after");
});
$( "#after" ).click(function() {
alert( "Handler for .click() called." );
});
});
</script>
</head>
<body>
<p id="before">TEST TEXT</p>
</body>
</html>
END;
?>
On hover over my test text, the color changes from maroon to blue, as expected. It is my understanding that the text would now have an ID of "after" and the click event handler function would apply when clicked. However that is not the case the quick event handler and its associated alert does not appear to trigger.
I am new to jquery is there perhaps an update handlers function I'm overlooking?
It works with the same principle as Event binding on dynamically created elements?.
When you add a event handler to an element where the element is found using a selector, the selector is executed only once when the code is executed after that the handler is added to the element. Once is has happend if you change the selector values associated with the element it will not reflect in the attached handlers.
For example in your case you are adding the a handler to the element with id before in dom ready handler, so once the dom ready event is fired your selector is evaluated and it returns a single element to which you are adding the handler. In the same dom ready handler you are trying to add a click handler to an element with id after, but at dom ready there are no elements with that id so that handler is not attached to any element.
Now at a later time you are changing the id of the elemnet, but it will not affect in the already attached handler nor will it add a new handler.
The solution here is to use a mechanism known as event delegation.
Demo:
$(document).ready(function() {
//there is no need to use hover as your want to add the class when the mouse enter the element and you don't want to do anything in mouseleave
$("#mytarget").mouseenter(function() {
$(this).addClass("after").removeClass('before');
});
//look at the use of event delegation
$(document).on('click', '.after', function() {
alert("Handler for .click() called.");
})
});
.before {
color: maroon;
}
.after {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="mytarget" class="before">TEST TEXT</p>
You can fire the click event after the hover event
$(document).ready(function(){
$("#before").hover(function() {
$(this).attr("id","after");
$( "#after" ).click(function() {
alert( "Handler for .click() called." );
});
return false;
});
});

Novice issue of this jQuery code not working

I'm really new to jQuery, and I want this code to show an alert box when the button is pressed.
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("button").click(function() {
alert("You clicked.");
});
</script>
<button>Button</button>
I try it, and nothing happens when I click the button.
In jQuery when event handlers are added, you need to make sure that the element is already loaded to the dom else jQuery selector will not return the element so the event handler will not get registered.
The solution is to use the dom ready event handler which will get triggered once the initial dom loading is completed meaning all the elements in the pages is loaded into the dom, it is the safest place to add the event handlers.
jQuery(function($){
$("button").click(function() {
alert("You clicked.");
});
})
As #zzzzBov noted below, it is a short cut for using the lengthy document ready handler
jQuery(document).ready(function($){
$("button").click(function() {
alert("You clicked.");
});
})
Right now, when your code executes, the button has not been loaded so it does not attach the click handler to anything, therefore you need to wrap your jQuery code in $(document).ready(function() { ... }); so that there is for sure a DOM element to attach your handler to, so your code becomes:
$(document).ready(function() {
$("button").click(function() {
alert("You clicked.");
});
});
See the documentation on $(document).ready().
Put your code in ready event
$(document).ready(function(){
$("button").click(function() {
alert("You clicked.");
});
});
You're calling jQuery to add the click handler before you're <button> is declared, so jQuery doesn't find it. Either move the <button> to the top of your snippet, or use a DOM ready function to delay your script execution until the DOM is ready to be manipulated.
Like this:
$(document).ready(function() {
$("button").click(function() {
alert("You clicked.");
});
});
You're running that script before the button exists, put it after instead:
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<button>Button</button>
<script>
$("button").click(function() {
alert("You clicked.");
});
</script>

Categories