I am able to bind click event to element with class name keybox. And this element is generated dynamically.
$('body').on('click','.keybox', function(){
// some code here
});
But for same element I tried binding hover and load event using following code:
$('body').on('hover','.keybox', function(){
// some code here
});
$('body').on('load','.keybox', function(){
// some code here
});
....and its not working as expected.
Can someone help with this problem? I want to bind hover and load event to my element with class name keybox and this element is generated dynamically.
Instead of hover, use mouseenter and mouseleave event. Instead of body.load use
$(document).ready(function() {
You can use following approach to bind multiple events and get object information via event object.
$('body').bind('click hover load', '.keybox', function(e){
if ( e.type === 'hover') {
// do something
}
else if(e.type === 'click') {
// do something
}
....
});
Make sure you bind events in $(document).ready(function() {} or load javascript just in bottom of html document body.
Since hover is deprecated you should use mouseenter and mouseleave for load you can write using event using on(load is equivalent to ready).
$(function(){
$(document).on('mouseenter', '.keybox', function () {
$(this).css('color','red');
});
$(document).on('mouseleave', '.keybox', function () {
$(this).css('color','black');
});
$(document).on('click', '.keybox', function () {// click on dynamically loaded events.
$(this).css('color','green');
});
$('#btn').click(function() {
$('#parent').append("<div class='keybox'>sample1</div>");
$('#parent').append("<div class='keybox'>sample2</div>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
zdhsdhsau
</div>
<input type="button" id="btn" value="create"/>
Related
The scenario I want to achieve is as follow:
$("#parentDiv").on("load",'#childDiv', function () {
// do something...
});
I would like to call a function when a child div is dynamically generated and shown on the page, but there is no suitable event that can achieve this. Any hint or help would be appreciated.
Instead of load, you can make use of a custom event which gets triggered with .trigger():
$(document).ready(function() {
$("button").on("click", function() {
$("body").append("<div id='new'>Created</div>").trigger('custom-event');
});
});
$(document).on("custom-event", function() {
console.log('DIV created!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button>Create element</button>
</body>
$(".btn").click(function()
{
$(".content").append(
"<div class='randomDiv' id='1'></div>"
);
}
If above is "active" then I cannot:
$(".randomDiv").click(function()
{
alert($(this.attr("id")));
}
I've googled and found out that it is because JS is loaded before I append, but haven't found a solution how to "register after load" on JS.
Either:
Attach the event handler when you create the element
$(".btn").click(function() {
$("<div class='randomDiv' id='1'></div>")
.on("click", myFunction)
.appendTo(".content");
}
function myFunction() {
alert($(this.attr("id")));
}
… so the element does exist when you bind the event handler
Use a delegated handler
$(document).on("click", ".randomDiv", function () {
alert($(this.attr("id")));
});
… that captures all the click events as they bubble up the document and checks which elements they came from.
$(".content").on('click', '.randomDiv', function()
{
alert($(this.attr("id")));
}
$(".content") can be replaced with any existing parent item of randomDiv. Say content div is inside page-left div then above code can be written as
$(".page-left").on('click', '.randomDiv', function()
{
alert($(this.attr("id")));
}
Or even
$(document).on('click', '.randomDiv', function()
{
alert($(this.attr("id")));
}
which bind event to the document level in DOM
Depending upon the version of jQuery you should use live, delegate, bind or on function.
If you append the element dynamically then the normal click function wont work. Use
$(document).on("click",".randomDiv",function(event){
alert($(this).attr("id"));
});
I have an inherited jQuery code where the scroll event has been set:
$(window).on('scroll', function(event) {
// Whatever
});
Now I need to add some more functionality to the previous code when a click event is fired, but this new code must be removed when another element is clicked, something similar to the below code:
$('#element1').on('click', function(){
$(window).on('scroll', function(event) {
// Add my code to the inherited one
});
});
$('#element2').on('click', function(){
$(window).on('scroll', function(event) {
// Unbind my code and leave the original behaviour
});
});
However, I cannot rewrite the inherited code. Is there any way to achieve this?
Thank you very much in advance
You can use event.namespace to bind the event. then you can use .off() to remove an event handler using namespace
$('#element1').on('click', function(){
$(window).off('scroll.element').on('scroll.element', function(event) {
// Add my code to the inherited one
});
});
$('#element2').on('click', function(){
$(window).off('scroll.element');
});
Using the above approach, default scroll event handler will have no impact.
Instead of binding scroll event to body you can bind it to body specific class. Clicking button will swap classes.
$(document).ready(function() {
$('.btn').click(function() {
$('.body')
.removeClass($(this).data('passive-class'))
.addClass($(this).data('active-class'));
});
});
.origin {
color: red;
}
.custom {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body">
Some content
<button class="btn" data-active-class="origin" data-passive-class="custom">Scroll origin</button>
<button class="btn" data-active-class="custom" data-passive-class="origin">Scroll custom</button>
</div>
Place all code inside function and use flag to execute as needed.
var additionalCode = false;
function usefulCode(event) {
// here is your default code
if (additionalCode) {
// here is additional code
}
}
$(window).on('scroll', usefulCode);
$('#element1').on('click', function(){
additionalCode = true;
});
$('#element2').on('click', function(){
additionalCode = false;
});
I have a $(document).ready function that sets up listeners for certain elements. However, all of the #leave-ride elements are added dynamically.
Listeners:
$(document).ready(function() {
$("#post-ride").click(function() {
addRide(currentDriver, $(destinationInput).val(), $(originInput).val(), $(dateInput).val(), $(timeInput).val());
$.getScript("scripts/myRides.js", function() {});
});
$("#request-ride").click(function() {
requestRide(currentDriver, $(destinationInput).val(), $(originInput).val(), $(dateInput).val(), $(timeInput).val());
$.getScript("scripts/myRides.js", function() {});
});
$("#leave-ride").click(function() {
console.log("leave Ride");
leaveRide(currentDriver, $("leave-ride").closest("div").attr("id"));
$.getScript("scripts/myRides.js", function() {});
});
});
What do I need to do to get that listener to listen to dynamic content?
Yes, ready runs only once. You can use event delegation:
Take the element closest to the #leave-ride which is not loaded dynamically (document in extreme cases). Then attach the handler on it, and use #leave-ride as the selector for the delegated event.
Assuming a div having the id #container is that static element:
$('div#container').on('click', '#leave-ride', function(){…});
See also Event binding on dynamically created elements?
Use on, change your event declaration
$("#post-ride").click(function() {
to
$("body").on('click',"#post-ride",(function() {
Use .on()
Example:
$("#leave-ride").on('click', function() {
console.log("leave Ride");
leaveRide(currentDriver, $("leave-ride").closest("div").attr("id"));
$.getScript("scripts/myRides.js", function() {
});
});
Is there another in jquery to run a function at page load and at a keyup event instead of the way I'm doing it?
$(function() {
totalQty();
$("#main input").keyup(function() {
totalQty();
});
});
Disregarding live or delegate optimizations, you can trigger an event like this:
$(function() {
$("#main input").keyup(function() {
totalQty();
}).filter(":first").keyup(); //Run it once
});
No need for the filter if it's not on multiple elements, just leave it out in that case.
You can use $(document).ready event to run functions on load:
$(document).ready(function(){
/* your code here */
});
Here's what I would do (jQuery 1.4+ )
$(document).ready(function() {
totalQty();
$("#main").delegate("input","keyup",function() {
totalQty();
});
});
You could use $.live(), which does event delegation, which is MUCH more efficient than created an event listener for every single input tag...and then missing any dynamically created ones. Try the following:
$(document).ready(function() {
totalQty();
$('#main input').live('keyup', function() {
totalQty();
});
});