What is the best way to bind a functions to multiple div's?
$('#trigger1').change(function(){
// same code
});
$('#trigger3').change(function(){
// same code
});
Either use class (imo is class the best way)
<div class="trigger"></div>
<div class="trigger"></div>
$('.trigger').change(function(){
});
or do this
$('#trigger1,#trigger3').change(function(){
});
You can include multiple ids in the same function call:
$('#trigger1, #trigger3').change(function(){
// code goes here
});
Or you can give them the same class, e.g. triggerClass and then call it like such:
$('.triggerClass').change(function(){
// code goes here
});
add a common class name to those div
<div class="myClass" id="trigger1">
</div>
<div class="myClass" id="trigger2">
</div>
here is the script for it
$(".myClass").click(function(){
// your code
});
$('#trigger1, #trigger3').change(some_function);
Or:
$('#trigger1').add('#trigger3').change(some_function);
simply apply a same class to all elements then write
$('.classname').change(function(){
});
you could use
$('#trigger1, #trigger3').change(function(){
same code
});
to group the triggers
Add a common class:
<div class="rowTrigger">trigger 1</div>
<div class="rowTrigger">trigger 2</div>
Script
$(function(){
$("body").on("click", ".rowTrigger", function(e){
e.preventDefault();
var row = $(this); //row element
});
});
each "rowTrigger" will fire on the "click" handler, this can be changed to other or multiple events. See
http://api.jquery.com/on/ for more detail.
The scope of the events handled can be changed by changing "body" to "table" for example, so it will only fire when those 'div' rows from a table are clicked.
More simply it can be written as (firing for 'click' and 'hover' ... but you get the idea) :
$("div.rowTrigger").on("click hover", function(e){
e.preventDefault();
var row = $(this); //row element
//some extra code
});
Related
On a page I have couple of divs, that look like this:
<div class="product-input">
<input type="hidden" class="hidden-input">
<input type="text">
<button class="remove">X</button>
</div>
I'm trying to bind an event to that remove button with this code (simplified):
$('.product-input').each(function() {
product = $(this);
product_field = product.find('.hidden-input');
product.on('click', '.remove', function(event) {
product_field.val(null);
});
});
It works perfectly when there is only one "product-input" div. When there is more of them, all remove buttons remove value from the hidden field from the last product-input div.
https://jsfiddle.net/ryzr40yh/
Can somebody help me finding the bug?
You dont need to iterate over the element for binding the same event. you can rather bind the event to all at once:
$('.product-input').on('click', '.remove', function(event) {
$(this).prevAll('.hidden-input').val("");
});
If the remove buttons are not added dynamically, you will not need event delegation:
$('.remove').click(function(event) {
$(this).prevAll('.hidden-input').val("");
});
Working Demo
You need to declare product and product_field as local variables, now they are global variables. So whichever button is clicked inside the click handler product_field will refer to the last input element.
$('.product-input').each(function() {
var product = $(this);
var product_field = product.find('.hidden-input');
product.on('click', '.remove', function(event) {
product_field.val(null);
});
});
Demo: Fiddle
But you can simplify it without using a loop as below using the siblings relationship between the clicked button and the input field
$('.product-input .remove').click(function () {
$(this).siblings('.hidden-input').val('')
})
Demo: Fiddle
I have the following divs:
<div class="celula" id="838">
</div>
<div class="celula" id="839">
</div>
<div class="celula" id="840">
</div>
I change them dynamically using jquery with an ajax response so far it works great.
Imagine that it generates the following:
<div class="checked" id="838">
</div>
<div class="checked" id="839">
</div>
<div class="checked" id="840">
</div>
Complete js callback:
$(document).ready(function () {
document.getElementById("templatenome").innerHTML = screen.width + " - " + screen.height;
$('.celula').on('mousedown', function(){
var template = $("#templatenome").attr("name");
var $div = document.getElementById (this.id);
$div.style.backgroundImage = "url('../../resources/"+template+"/images/CelulaPOP.png')";
var audio = document.getElementById("audio");
audio.play();
$(document).one('mouseup', function(){
sendAjax($div.id);
$div.style.backgroundImage = "url('../../resources/"+template+"/images/CelulaSEL.png')";
});
});
$(document).on('mousedown', '.checked', function(){
$(document).one('mouseup', function(){
});
});
});
Use a delegated event handler, attached to a non-changing ancestor of the dynamic elements:
$(document).on('mousedown', '.checked', function(){
$(document).one('mouseup', function(){
alert("I was mouse-uppped on a .checked div!");
});
});
As you do not want the previous handler to operate once the class is changed (see comments below), make that a delegated handler too:
e.g.
$(document).on('mousedown', '.celula', function(){
This applies the jQuery selector at event time only, so the elements only need to match then (and not when the event was registered).
document is the best default if nothing closer is available/convenient. Do not use 'body' as it has a bug (if styling results in a calculated body height of 0 it will not bubble mouse events to body)
Here is a little demo showing how events will fire with the delegated event handlers as the classes are changed:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5xb6vohp/3/
I have:
$(document).ready(function() {
$("#btn1").click(function() {
$("#po").append("<p><%= j f.datetime_select :dtmRealshow%><a>Remove</a></p>");
});
});
<p id="po"></p>
<button id="btn1">+</button>
When i click on the btn1 a new datetime_select field is added to the form.But i want to remove the parent <p> tag after clicking on the remove link.Please help me out.
Add a css class to anchor
$("#po").append("<p><%= j f.datetime_select :dtmRealshow%><a class='remove'>Remove</a></p>"); });
Then you can use Event Delegation using .on() delegated-events approach to bind click handler to anchor.
$("#po").on('click', ".remove", function(){
$(this).closest('p').remove();
});
Removing the parent <p> will remove it's children along with it.
If that's what you're looking for then try the following code.
$(document).ready(function(){
$("#btn1").click(function(){
$("#po").append("<p><a id='remove'>Remove</a></p>");
$("#remove").click(function() {
$(this).closest('p').remove();
});
});
});
Here is the demo
I have a list of blocks, for each block their is a css change by jquery on mouseover/out.
I have a button that is job is to add one more block to the list.
It do it great! But the new block not respond to the mouseover/out jquery set.
This is my blocks and the add:
<div class='blocks'>
<div class='block'>
<div class='block-top'></div>
Default Text Here
</div>
<div class='block'>
<div class='block-top'></div>
Default Text Here
</div>
<div class='block'>
<div class='block-top'></div>
Default Text Here
</div>
</div>
<a href='#' id='addBlock'>Add Block</a>
And this is the javascipt:
$(document).ready(function() {
var inEdit=0;
$(".block").hoverIntent(function() {
if(inEdit==0) {
$(this).children('.block-top').delay(300).animate({opacity:1},600);
$(this).delay(300).animate({borderColor: '#8f8f8f'},600);
}
},function() {
if(inEdit==0) {
$(this).children('.block-top').animate({opacity:0},200);
$(this).animate({borderColor: '#ffffff'},200);
}
});
$('#addBlock').click(function() {
$('.blocks').append("<div class='block'><div class='block-top'></div>Default Text Here</div>");
});
});
I'm using this two scripts:
http://www.bitstorm.org/jquery/color-animation/
http://cherne.net/brian/resources/jquery.hoverIntent.html
What can I do?
Thanks
If you wish that future elements benefits from the event, you have to use on : http://api.jquery.com/on/
For instance :
$('#addBlock').on('click', function() {
$('.blocks').append("<div class='block'><div class='block-top'></div>Default Text Here</div>");
});
You are binding the hoverintent to the element which doesnt exist on load. Therefore the new element wont get the event handler. You have to use .Delegate() or .on()/.off() depending on your version of jQuery Information on how to use each can be found below
http://api.jquery.com/delegate/
http://api.jquery.com/on/
However as hoverIntent uses jquerys mouseover i dont know if it has a specific eventType you can use for delegate/on
This question is about using hoverIntent on new elements. There is exactly this other thread about the same thing, check out the answer :
help with understanding the logic behind how javascript executes on new dom elements being created on the fly
make use of jquery live() method, i.e) use below codes
$(".block").live('hoverIntent', function() { //this line is modified
if(inEdit==0) {
$(this).children('.block-top').delay(300).animate({opacity:1},600);
$(this).delay(300).animate({borderColor: '#8f8f8f'},600);
}
},function() {
if(inEdit==0) {
$(this).children('.block-top').animate({opacity:0},200);
$(this).animate({borderColor: '#ffffff'},200);
}
});
make some adjustments to add 2 functions for the event 'hoverIntent'. I mean this will work
$(".block").live('hoverIntent', function() { //this line is modified
if(inEdit==0) {
$(this).children('.block-top').delay(300).animate({opacity:1},600);
$(this).delay(300).animate({borderColor: '#8f8f8f'},600);
}
});
but to have 2 functions you can try like
$(".block").live('hoverIntent', function() { //this line is modified
if(inEdit==0) {
$(this).children('.block-top').delay(400).animate({opacity:1},600);
$(this).delay(400).animate({borderColor: '#8f8f8f'},600);
}
if(inEdit==0) {
$(this).children('.block-top').animate({opacity:0},200);
$(this).animate({borderColor: '#ffffff'},200);
}
});
I have a nested div like this
<div id="one">
<div id="two">
id two goes here
</div>
<div id="three">
id three goes here
</div>
<div id="four">
id four goes here
</div>
</div>
Now i want to handle click and doubleclick events on all divs except in div#four,
like this
$('#one').live('dblclick', function() {
my javascript code goes here
});
('#one').live('click', function() {
my javascript code goes here
});
How can i use the above script and exclude the last nested div #four.
Thanks
Like this:
$('#one, #one > div').not('#four').delegate('dblclick, click', function(){
// my javascript code goes here
});
EDIT: Based on further clarification, try this:
$('#one').bind('click dblclick', function( event ) {
var id = event.target.id;
if(id == "one" || id == "two" || id == "three") {
if(event.type == "click") {
// code for click event
} else {
// code for double click event
}
}
});
EDIT: Based on our conversation under another answer, it seems like you want the #one element to be clickable, but none of its child elements. If that is right, try this:
$('#one').click(function() {
// code to run when `one` is clicked.
}).children().click(function( event ) {
event.stopPropagation();
});
Now if there's any text in #one, the code for that element will fire, but it will not fire when you click any children of #one.
Let me know if that was what you wanted.
EDIT:
If you are saying that you will have a dynamic number of elements inside #one, and the last one will not get the event, then do this:
$('#one').delegate('div:not(:last-child)', 'click dblclick', function( event ) {
if(event.type == 'click') {
// do something for the click event
} else {
// do something for the double click event
}
});
Note that this assumes there will not be nested divs. Results may be unexpected if there are. Also, the #one element doesn't fire events. Only its children.
Original answer:
$('#one,#two,#three').bind('click', function(){
// code for click event
})
.bind('dblclick', function() {
// code for double click event
});
Or replace .bind with .live if you really need it.
I would use an additional class:
HTML:
<div id="one">
<div id="two" class="clickable">
id two goes here
</div>
<div id="three" class="clickable">
id three goes here
</div>
<div id="four">
id four goes here
</div>
</div>
JS:
('.clickable').live('click', function() {
});
Use not method, more on this here: How can I exclude these elements from a jQuery selection?
You must use $('#one') instead $('.one') aren't you?
$("div:not(#four)")
or
$("#one :not(#four)")
Will select any div that does not have the id="four" set. Basically the :not is what you are looking for. Anything in the :not parenthesis is negated for selection purposes.
http://api.jquery.com/not-selector/
An alternative is to attach a single click/double click handler to the parent which means no need for .live or anything, and in the handler ensure that you are receiving a click from an acceptable child with $(event.target).is(":not(#id)")
$("#one").click(function(event) {
if (this != event.target && $(event.target).is(':not(#four)')) {
// do work on event.target
}
});
// ...