jQuery .on() does not trigger any events [duplicate] - javascript

This question already has answers here:
Event handler not working on dynamic content [duplicate]
(2 answers)
Closed 9 years ago.
I am writing an application using jQuery, where when a button is clicked, a select box is generated and appended to a row. Whenever the select changes, it should trigger the change event, but using .on("change", function() {}); isn't working:
Code:
<!DOCTYPE html>
<html>
<head>
<title>HTML5-Template</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<style type="text/css">
html, body
{
}
input,select {
border: 1px solid #404048;
padding: 4px;
}
</style>
<script type="text/javascript" src="../JavaScript/JQuery/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#cmdCreateRow").click(function() {
var row = $("<div />")
.css("font", "normal 12px Verdana")
.css("padding", "8px")
.css("display", "inline-block")
.css("background", "#F0F0F8")
.css("border", "1px solid #A0A0A8")
.css("margin", "2px");
var types = [
"Local",
"Remote",
"(Custom)"
];
var type = $("<select />").attr("class", "member-type");
for(var i in types) {
type.append($("<option />").val(types[i]).text(types[i]));
};
row.append(type);
$("#Container").append(row).append($("<br />"));
});
$(".member-type").on("change", function() {
alert("changed");
});
});
</script>
</head>
<body>
<input type="button" id="cmdCreateRow" value="Create Row" />
<div id="Container">
</div>
</body>
</html>
Any idea's what I'm doing wrong?

As $(".member-type") is empty when you do the binding, you're not doing anything.
Change
$(".member-type").on("change", function() {
alert("changed");
});
to
$(document).on("change", ".member-type", function() {
alert("changed");
});
or this because the #Container element is static:
$("#Container").on("change", ".member-type", function() {
alert("changed");
});

Try this:
$(document).on("change", ".member-type", function() {
//Code
});
This is the replacement for: "live" in jQuery, see: http://api.jquery.com/live/
--
The regular "on" method will only work for elements which are already available in the DOM.

Related

Element created on keydown using JavaScript createElement() method won't work with the jQuery draggable() method

I'm working on a drag and drop project where items can be added to a work area and dragged to be positioned. I am trying to use a key code to create multiple of the same kind of element, all of which can be dragged. The jQuery function works as long as the draggable element is created when the page loads, but if it's created using a function, the draggable() method isn't working on it. Is there a way to get the function to recognize the element created with a function?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Draggable Div Test</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
.test {
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<div id="area" style="border: 1px solid black; width: 500px; height: 500px;"> </div>
<script>
var area = document.getElementById("area");
function duplicate(e) {
switch(e.keyCode) {
case 49:
var test = document.createElement("div");
test.classList.add("test");
test.classList.add("draggable");
console.log(test.classList)
test.style.backgroundColor = "blue";
area.appendChild(test);
break
}
}
document.addEventListener("keydown", duplicate)
$( function() {
$( ".test" ).draggable();
} );
</script>
</body>
</html>
Thanks
jQuery draggable has a function called clone:
$(function() {
i = 0
$("#draggable").draggable({
helper: 'clone',
appendTo: "#droppable",
});
$("#droppable").droppable({
accept: "#draggable",
});
i++;
var $obj = ui.helper.clone().attr( 'data-name', 'newelementdropped' +i).draggable({
stop : function (event, ui) {
YOUR CODE
});
}
See this answer: Jquery draggable(), clone() to append div...Pls Fiddle my jsfiddle
Just re-initalize the plugin after you insert the element.
Something like:
$(".test").draggable("destroy").draggable();

Wrong function called after class toggle

I'm facing such problem. I have div with class oldClass and function that toggle div's class on click. When the class changed clicking on div should trigger other function and call alert, however this behavior doesn't appear and it seems like previous function is called again. I'm quite new in jQuery, so what am I missing?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('.oldClass').on('click',function(){
$(this).toggleClass('oldClass').toggleClass('newClass');
});
});
$(function(){
$('.test').on('click',function(){
alert('1111');
});
});
</script>
<style>
.oldClass {
border: 1px solid red;
}
.newClass {
border: 3px solid green;
}
</style>
</head>
<body>
<div class="oldClass" title="qwerty">qwerty
</div>
<body>
</html>
Here you go! You have to subscribe and unsubscribe to events. I'm new to jQuery as well and it might be not the clearest solution, but it works. If anyone can suggest a better solution, you are welcome.
var subNewClass = function () {
$('.newClass').off().on('click', function () {
alert('1111');
});
};
var subOldClass = function () {
};
$(function () {
$('.oldClass').off().on('click', function () {
$(this).toggleClass('oldClass').toggleClass('newClass');
$('.newClass').off().on('click', func);
});
});
.oldClass {
border: 1px solid red;
}
.newClass {
border: 3px solid green;
}
<div class="oldClass" title="qwerty">qwerty</div>
You're declaring document.ready twice ... $(function(){}); is a shortand for $(document).ready(); and not a javascript function declaration ...
To create a function you should first do function foo(){ /* content goes here */ }; or var foo = function(){ /* content goes here */ }; ant then call it whenever you want by writing foo();
Read more about JS functions here
Check this to see how this should work: JSFIDDLE DEMO
var alertTrigger = function (){
$('.newClass').on('click',function(){
$(this).toggleClass('oldClass').toggleClass('newClass');
alert('1111');
});
}
$(function(){
$('.oldClass').on('click',function(){
$(this).toggleClass('oldClass').toggleClass('newClass');
alertTrigger();
});
});

jquery onclick new element not created properly [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 9 years ago.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery UI Button - Icons</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<style>
#s
{
width:200px;
}
#div1
{
min-width:100px;
width:auto;
float:left;
border:2px solid black;
min-height:100px;
height:auto;
background-color:red;
}
</style>
<script>
$(document).ready(function(){
$("div").click(function(){
$(this).after($('<div id="s" style="background-color:blue;">NLC TRANSPORT</div>'));
});
$("#s").click(function(){
alert("sljsdf");
});
});
</script>
</head>
<body>
<div id="div1">
VOLVO B9R
</div>
</body>
</html>
Here when i click on the first div, the program creates another div. the newly created div is not responding to on click event. in the current code i have specified that the newly created div should give an alert on click but its not working.
Thanks!
You need event degation for dynamically added elements. The time the binding code for element with id s is executed the element does not exists in DOM
$(document).on("click", "#s", function(){
alert("sljsdf");
});
Delegated events
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers, jQuery doc.
When your dom ready handler is executed the #s div does not exists in the dom, so the click handler will not get added to the element. You can use event delegation to fix this problem
$(document).on('click', "#s", function () {
alert("sljsdf");
});
Demo: Fiddle
try something like this
$("body").on('click','#s',function(){
alert("sljsdf");
});
REFERENCE
http://api.jquery.com/on/
Since the #s element are created dynamically you need to use event delegation to register event handlers to these elements.
When you use $('#s').click(....); to register an event handler it will register the handle to only those elements which are already present in the dom at the time of the code execution, in you case since these elements are created after that the handlers will not get attached to the newly created elements
Try this
$(document).ready(function(){
$(document).on('click',"div",function(){
$(this).after($('<div id="s" style="background-color:blue;">NLC TRANSPORT</div>'));
});
$(document).on("click", "#s", function(){
alert("sljsdf");
});
});
DEMO
Please see this LINK
OR
Try below code...
Your HTML ....
<div id="div1"> VOLVO B9R </div>
Your JQuery Code....
$(document).ready(function () {
$("div").click(function () {
$(this).after($('<div id="s" style="background-color:blue;">NLC TRANSPORT</div>'));
$("#s").bind('click', function () {
alert("sljsdf");
});
});
});
Your CSS....
#s
{
width:200px;
float:right;
}
#div1
{
min-width:100px;
width:auto;
float:left;
border:2px solid black;
min-height:100px;
height:auto;
background-color:red;
}
Use below code..
$(document).ready(function () {
$("div").click(function () {
$(this).after($('<div id="s" style="background-color:blue; clear:both">NLC TRANSPORT</div>'));
$("#s").bind("click", function () {
alert("sljsdf");
});
});
});
Good luck.
The following jQuery lines of code will help you..
$(document).ready(function(){
$('body').on('click','#div1',function(){
$(this).after($('<div id="s" style="background-color:blue;">NLC TRANSPORT</div>'));
$('#s').click(function(){
alert('a');
})
})
});
You can't add an event handler to an element that doesn't exist yet:
$(document).ready(function () {
$("div").click(function () {
$(this).after($('<div id="s" style="background-color:blue;">NLC TRANSPORT</div>'));
$("#s").click(function () {
alert("sljsdf");
});
});
});
Try This Code :
$(document).ready(function(){
$("#div1").click(function(e){
$(this).after($('<div id="s" style="background-color:blue;">NLC TRANSPORT</div>'));
$("#s").click(function(){
alert("sljsdf");
});
});
});

jQuery: Highlight div box onload

This jQuery code will highlight the div box when clicked.
I want to get the highlight on load, how can I do that?
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<style type="text/css">
div { margin: 0px; width: 100px; height: 80px; background: #666; border: 1px solid black; position: relative; }
</style>
<script>
$(document).ready(function() {
$("#div1").click(function () {
$(this).effect("highlight", {}, 3000);
});
});
</script>
</head>
<body">
<div id="div1"></div>
</body>
</html>
Put the statement for highlight in document.ready at the same level you are binding click event..
Live Demo
$(document).ready(function() {
$("#div1").effect("highlight", {}, 3000); //this will highlight on load
$("#div1").click(function () {
$(this).effect("highlight", {}, 3000);
});
});
Alternatively, this way might be a little cleaner in that if you add some other effects that you want to show on the click state, you only need to define them one time.
$(document).ready(function() {
$("#div1").click(function () {
$(this).effect("highlight", {}, 3000);
});
$('#div1').click();
});
Javascript
$(document).ready(function() {
$("#div1").effect("highlight", {}, 3000);
});
This will highlight the div1 when the document is ready. If you also want a click handler, you can keep it and put in whatever code you want (ie. you can also keep the effect in there as well, if you want to).
Fiddle

jQuery UI Sortable -- How can I cancel the click event on an item that's dragged/sorted?

I have a jQuery UI Sortable list. The sortable items also have a click event attached. Is there a way to prevent the click event from firing after I drag an item?
$().ready( function () {
$('#my_sortable').sortable({
update: function() { console.log('update') },
delay: 30
});
$('#my_sortable li').click(function () {
console.log('click');
});
});
#my_sortable li {
border: 1px solid black;
display: block;
width: 100px;
height: 100px;
background-color: gray;
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
<ul id="my_sortable">
<li id="item_1">A</li>
<li id="item_2">B</li>
<li id="item_3">C</li>
</ul>
I had the same problem and since my sortable items contained three or four clickable items (and the number was variable) binding/unbinding them on the fly didn't really seem an option. However, by incident I specified the
helper : 'clone'
option, which behaved identically to the original sortable in terms of interface but apparently does not fire click events on the dragged item and thus solves the problem. It's as much a hack as anything else, but at least it's short and easy..
If you have a reference to the click event for your li, you can unbind it in the sortable update method then use Event/one to rebind it. The event propagation can be stopped before you rebind, preventing your original click handler from firing.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
<script type="text/javascript" charset="utf-8">
var myClick = function () {
console.log('click');
};
$().ready( function () {
$('#my_sortable').sortable({
update: function(event, ui) {
ui.item.unbind("click");
ui.item.one("click", function (event) {
console.log("one-time-click");
event.stopImmediatePropagation();
$(this).click(myClick);
});
console.log('update') },
delay: 30
});
$('#my_sortable li').click(myClick);
});
</script>
<style type="text/css" media="screen">
#my_sortable li {
border: 1px solid black;
display: block;
width: 100px;
height: 100px;
background-color: gray;
}
</style>
</head>
<body>
<ul id="my_sortable">
<li id="item_1">A</li>
<li id="item_2">B</li>
<li id="item_3">C</li>
</ul>
</body>
</html>
If you for some reason don't want to use the helper:'clone' trick, this worked for me. It cancels the click event on an item that is dragged. jQuery adds the class ui-sortable-helper to the dragged element.
$('.draggable').click(clickCancelonDrop);
function clickCancelonDrop(event) {
var cls = $(this).attr('class');
if (cls.match('ui-sortable-helper'))
return event.stopImmediatePropagation() || false;
}
$('.selector').draggable({
stop: function(event, ui) {
// event.toElement is the element that was responsible
// for triggering this event. The handle, in case of a draggable.
$( event.toElement ).one('click', function(e){ e.stopImmediatePropagation(); } );
}
});
This works because "one-listeners" are fired before "normal" listeners. So if a one-listener stops propagation, it will never reach your previously set listeners.
We can also use a flag on the stop event that and check that flag on the click event.
var isSortableCalled = false;
$('#my_sortable').sortable({
stop: function(event, ui){
isSortableCalled = true;
},
update: function() { console.log('update') },
delay: 30
});
$('#my_sortable li').click(function () {
if(!isSortableCalled){
console.log('click');
}
isSortableCalled = false;
});
The answer by mercilor worked for me a couple of caveats. The click event was actually on the handle element rather than the sorted item itself. Unfortunately the ui object, doesn't give you a reference to the handle in the update event (feature request to jquery ui?). So I had to get the handle myself. Also, I had to call preventDefault as well to stop the click action.
update: function(ev, ui) {
var handle = $(ui.item).find('h3');
handle.unbind("click");
handle.one("click", function (event) {
event.stopImmediatePropagation();
event.preventDefault();
$(this).click(clickHandler);
});
// other update code ...
Easier, use a var to know when the element is being sorted...
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
<script type="text/javascript" charset="utf-8">
$().ready( function () {
$('#my_sortable').sortable({
start: function() {
sorting = true;
},
update: function() {
console.log('update');
sorting = false;
},
delay: 30
});
$('#my_sortable li').click(function () {
if (typeof(sorting) == "undefined" || !sorting) {
console.log('click');
}
});
});
</script>
<style type="text/css" media="screen">
#my_sortable li {
border: 1px solid black;
display: block;
width: 100px;
height: 100px;
background-color: gray;
}
</style>
</head>
<body>
<ul id="my_sortable">
<li id="item_1">A</li>
<li id="item_2">B</li>
<li id="item_3">C</li>
</ul>
</body>
</html>
Thanks to Elte Hupkus;
helper: 'clone'
I have implemented the same and a sample is shown below.
$(document).ready(function() {
$("#MenuListStyle").sortable({
helper:'clone',
revert:true
}).disableSelection();
});
One solution is to use live() instead of normal binding, but Elte Hupkes solution rocks!!!!
$('.menu_group tbody a').click(function(){
link = $(this).attr('href');
window.location.href = link;
});
This solution seems to be working for me. Now i can click on clickables inside sortable elements.
Note: ".menu_group tbody" is .sortable();

Categories

Resources