How to attach event to the newly added anchor using jquery - javascript

I trying to attach a click event for the newly added anchor tag(.he) after the #foo anchor tag. But the click event is not happening. I have used (.on). Can you guys help me in this ?*
<!DOCTYPE html>
<html>
<head>
<title>Attaching event</title>
<style>p { background:yellow; margin:6px 0; }</style>
<script src="js/jquery.js"></script>
</head>
<body>
<p>Hello</p>
how are
<p>you?</p>
<button>Call remove() on paragraphs</button>
<a id="foo" href="#" style="display:block">Testing the bind and unbind</a>
<script>
$("button").on('click',function () {
$("#foo").after("<a class='he' href='#'>asdfasdf</a>");
});
$(".he").on('click', function(){
alert("test");
});
</script>
</body>

You have to delegate to a static parent element like this
$(document).on('click','.he',function(){
//code here
});

Use event delegation
$("body").on("click", ".he", function() {
alert("test");
});
Instead of body you can use any static parent element of .he.

use .live. and don't forget to add your code inner jquery clousure
<script>
$(function(){
$("button").on('click',function () {
$("#foo").after("<a class='he' href='#'>asdfasdf</a>");
});
$(".he").live('click', function(){
alert("test");
});
});
<script>

you will have to put the below code inside $("button").click block.
$(".he").on('click', function(){
alert("test");
});
Link for jsfiddle http://jsfiddle.net/wbWLE/

You can instead bind the click event to the anchor before appending it to the DOM like this:
var $he = $("<a class='he' href='#'>asdfasdf</a>").on('click', function(){
alert("test");
})
$("#foo").after($he);

You can either attach a handler to the anchor directly before it is appended into the document:
$("button").on('click',function () {
$("<a class='he' href='#'>asdfasdf</a>")
.on('click', function(){
alert("test");
})
.insertAfter("#foo");
});
or bind a delegate handler on the document that will catch all clicks on anchors with he as their class:
$(document).on('click', 'a.he', function() {
alert("test");
});
$("button").on('click',function () {
$("<a class='he' href='#'>asdfasdf</a>").insertAfter("#foo");
});

Related

How can i add a event function after append a elements?

I click the button, it will append a div inside body, then, I want to click the div to alert a msg.I tried, but fail. How can I implements with highlight area.
example
$(document).ready(function()
{
$("button").click(function()
{
div = "<div class='test'>div</div>";
$("body").append(div);
});
$(".test").click(function()
{
alert("test");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Append div</button>
You should note that when document is ready elements with the .test class do not exist (that is why your code didn't work), they are dinamically added. So, I will do like this:
$(document).ready(function()
{
$("button").click(function()
{
var div = $("<div></div>").addClass('test'); // this is creating div element in dom as jquery
// Then attach click function to purpose of its create
div.click(function()
{
alert('test')
});
$("body").append(div);// then this is appending created div
});
});
jsfiddle Playground
One way, is just registering the listener on click event after you append it to the body tag, taking care of unregistering the previous clicks events, so you don't fall on multiple clicks events on the same element. Note that when document is ready still don't exists any element with the class .test, thats the reason your code was not working. Check next example:
$(document).ready(function()
{
$("button").click(function()
{
var div = "<div class='test'></div>";
$("body").append(div);
$(".test").unbind("click").click(function()
{
alert("A new div was clicked!");
});
});
});
.test {
width: 200px;
height: 200px;
background: red;
margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button type="button">Append new div</button>
</body>
For dynamically created elements, use .on, lear more about .on here http://api.jquery.com/on/
$(document).ready(function(){
$("button").click(function(){
div = "<div class='test'></div>";
$("body").append(div);
});
$(document).on('click', '.test', function(){
alert("test");
});
});

How to have multiple functions in jQuery ready?

I can create Jquery functions, but what if you want more functions.
For example say I wanted to have a function for a drop down list AND a button.
I can only seem to do one function:
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
this.hide();
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("banner").click(function() {
this.fadeTo();
});
});
</script>
Is this right on how to create multiple functions in one document or is there an easier way to create them?
Can you show me how to create multiple ones instead of one?
Both functions can go inside the same document ready function:
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$(this).hide();
});
$("banner").click(function()
$(this).fadeTo();
});
});
</script>
However, the selector $("banner") is invalid, if you're targeting a class of banner it should be $(".banner"), ID would be $("#banner")
You should rather use single document ready event and then wrap the two methods in it.
You would need to use class selector as element have class banner in it.also double quote is missing at the end of this selector
:
$(document).ready(function() {
$("button").click(function() {
$(this).hide();
});
$(".banner").click(function() {
$(this).fadeTo();
});
});
You can put them in the same $(document).ready function - you don't need a new document ready for each event listener.
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$(this).hide();
});
$("banner).click(function() {
$(this).fadeTo();
});
});
</script>
Also your $("banner") selector is invalid - take a look at the jQuery Selectors documentation here: https://api.jquery.com/category/selectors/
you only require one $(document).ready(function () {})
<script type="text/javascript">
$(document).ready(function () {
$("button").click(function () {
$(this).hide();
});
$("banner").click(function () {
$(this).fadeTo();
});
});
</script>
Combine both and change $("banner) to $(".banner"):
$(document).ready(function() {
$("button").click(function() {
$(this).hide();
});
$(".banner").click(function()
$(this).fadeTo();
});
});
concat button & banner click code in $(document).ready:
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$(this).hide();
});
$("banner").click(function() {
$(this).fadeTo();
});
});
</script>
If you are going to use the code several time it is fairly easy to write a function that hides a certain element. Then you just have to call the function with a parameter(the value of your DOM.
function hideElement(value)
{
$('' + value +' ').click(function() {
$(this).fadeTo();
});
$(document).ready(function() {
hidedElement(banner);
hideElement(button);
});

JQuery- Change the id of an element and call a function on click

I have an element with some id, I changed its ID and when I click on that element (with new ID now), it still calls the function with previous ID
$('#1st').click(function(){
$('#1st').attr('id','2nd');
alert("id changed to 2nd");
});
$('#2nd').click(function(){
alert("clicked on second");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Click
Example is here
Because you add the event before the element exists. It does not find an element. Either attach the event when you change the id or you need to use event delegation.
$('#1st').on("click.one", function(e) {
$('#1st').attr('id', '2nd');
alert("id changed to 2nd");
e.stopPropagation();
$(this).off("click.one");
});
$(document).on("click", '#2nd', function() {
alert("clicked on second");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Click
Try doing it this way jsFiddle
$(document).on('click', '#2nd', function(){
alert("clicked on second");
})
.on('click', '#1st', function(e) {
$('#1st').attr('id','2nd');
alert("id changed to 2nd");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Click
Also see this post on using Jquery's .on() versus .click()

Trigger click function on load

I have the following function which is activated on click:
$('.results .view-rooms').click(function(){ }
Is there anyway I can trigger this function on document load?
Yes.
$(document).ready(function(){ // on document ready
$(".results .view-rooms").click(); // click the element
})
$('.results .view-rooms').click()
You can put it in DOM ready:
$(function(){
$('.results .view-rooms').click()
});
Or window load:
$(window).load(function(){
$('.results .view-rooms').click();
});
Note that there is no such event document load.
We have DOM ready or window load
$(document).ready(function(){ $('.results .view-rooms').click(); });
Considering that you're already using jQuery to bind the event handler, and assuming that code is already in a position where the entire DOM has been constructed, you can just chain the call to .click() to then trigger that event handler:
$('.results .view-rooms')
.click(function(){...}) //binds the event handler
.click(); // triggers the event handler
Put the code inside
$(function(){ // code here });
like:
$(function(){
$(".results .view-rooms").click();
});
or
$(function(){
$(".results .view-rooms").trigger('click');
});
$(function(){
$('.results .view-rooms').click(function(){
}
$(".results .view-rooms").trigger('click');
}
The best way is:
html form:
<form action="https://stackoverflow.com" method="get">
<button id="watchButton"></button>
</form>
End Jquery:
<script>
$('document').ready(function() {
$('#watchButton').click();
});
</script>
JQuery Version:
https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js

Why is my event handler bound with jQuery not firing?

Any ideas why this doesnt work in my php document?
When i tested this on jsfiddle, everything worked fine.
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$("a").click(function() {
$("div.info").hide();
$("div." + this.className).show();
});
</script>
</head>
<body>
<div class="shipping-container">
Show UPS info
Show Fedex info
<div class="ups info" style="display:none">the info for ups</div>
<div class="fedex info" style="display:none">Who let the dogs out</div>
</div>
</body>
You missed the document ready handler, try this:
<script type="text/javascript">
$(function() {
$("a").click(function() {
$("div.info").hide();
$("div." + this.className).show();
});
});
</script>
Alternatively, leave your script tag as it is, but put it at the end of the document, before the </body> tag.
You should make sure that your JQuery code is only loaded AFTER your DOM has fully loaded by doing:
$(document).ready(function() {
$("a").click(function() {
$("div.info").hide();
$("div." + this.className).show();
});
});
You are running the script before the link element exists.
In jsfiddle the code is by default placed in an event that runs after the document is loaded. Use the ready event to do this in your code:
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function() {
$("div.info").hide();
$("div." + this.className).show();
});
});
</script>
I think you should do this in your header:
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
$("div.info").hide();
$("div." + this.className).show();
});
</script>
This will ensure that all of the DOM objects (especially the a elements) are loaded before you try to attach any event handler.

Categories

Resources