This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 9 years ago.
i am building a web app. the main navigation of this web app is refreshed with jquery but after the refresh the jquery event doesnt work.
the "on button" has a jquery event bound to it with .on and everytime it is clicked it will append a paragraph. the "reset button" adds another "on button" but the jquery event doesn't apply to it.
i have used the .on method to circumvent that the second "on button" isn't in the DOM when the document is ready.
here is a simple example:
example on jsFiddle
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>blub</title>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".reset").click(function() {
$("nav").append('<button class="on">test</button>');
})
var count = 0;
$(".on").on("click", function(){
$(".cont").append("<p>Another paragraph! "+(++count)+"</p>");
});
});
</script>
</head>
<body>
<button class="reset">reset</button>
<nav>
<button class="on">test</button>
</nav>
<div class="cont"></div>
<script>
</script>
</body>
</html>
.on isn't a direct replacement for .live, its syntax is slightly different. If you want it to affect elements added to the DOM later, you need to use it like this:
$(document).on('click', '.on', function(){
});
The problem is hot you use method "on" try this:
<script type="text/javascript">
$(document).ready(function() {
$(".reset").click(function() {
$("nav").append('<button class="on">test</button>');
})
var count = 0;
$(document).on("click",".on", function(){
$(".cont").append("<p>Another paragraph! "+(++count)+"</p>");
});
});
</script>
DEMO
You could also do it very simply this way -- this way the click handler gets assigned to each button as it is created.
$(document).ready(function() {
var count = 0;
$(".reset").click(function() {
$("nav").append($('<button>', {
class: 'on',
html: 'test',
click: function() {
$('.cont').append('<p>Another paragraph! ' + (++count) + '</p>');
}
}));
});
});
Related
I’ve this script. It works fine in this situation, but it seems to conflict with other scripts in the site I'm working on. How can I rewrite it that it doesn't need jQuery / OnLoad?
This is what it does: the button opens a random link from an array in a new window everytime you click on it.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.js"></script>
<title>TestBase</title>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
var links = [
"http://vetteletters.nl",
"http://todont.co",
"http://planetx.nl/titles"
];
$("#rnd_link").click(function(){
window.open(links[Math.floor((Math.random()*3))]);
});
});//]]>
</script>
</head>
<body>
<button id="rnd_link">Random</button>
</body>
</html>
window.onload = function(){
var links = [
"http://vetteletters.nl",
"http://todont.co",
"http://planetx.nl/titles"
];
var btn = document.getElementById('rnd_link');
btn.onclick = function(){
window.open(links[Math.floor((Math.random()*3))]);
}
}//]]>
Should work.
This works:
<script type='text/javascript'>
var links = [
"http://vetteletters.nl",
"http://todont.co",
"http://planetx.nl/titles"
];
window.addEventListener('load', function() {
document.getElementById("rnd_link").onclick = function() {
window.open(links[Math.floor((Math.random()*3))]);
};
});
</script>
If you just want to avoid using jQuery, I suggest using window.onload to trigger the function when the page loads.
window.onload = function(){
// do stuff
};
Then in order to select a DOM element, you'll use the getElementById() method, then you'll add an event listener for a mouseclick:
document.getElementById("rnd_link").addEventListener("click", function(){
// do stuff
});
Here's the MDN entry for event listeners for further reading: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
I'd suggest this:
Call the function when the button is clicked.
<button id="rnd_link" onclick="random()"></button>
<script>
var links = [
"http://vetteletters.nl",
"http://todont.co",
"http://planetx.nl/titles"
];
function random(){
window.open(links[Math.floor((Math.random()*3))]);
}
</script>
More info for onclick here
I am trying to customize some public git, and because I am a noob in Jquery/Javascript I do not know how to properly bind an onclick function to the button, so that it will know how to call getStates() function. Yes I know that I could just remove $(function(){ and it would work, but I want to be able to call it within jquery function ?
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>US Hospitals</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox.js/v2.2.3/mapbox.js'>
</script>
<link href='https://api.mapbox.com/mapbox.js/v2.2.3/mapbox.css' rel='stylesheet' />
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="/lib/neo4j-web.min.js"></script>
</head>
<body>
<div id="desc">
<div class="row top-row">
<div class="col-xs-6">
<h3 class="heading">US Hospitals</h3>
</div>
<div class="col-xs-6">
<p class="lead"></p>
</div>
<button onclick="$.getStates();">Load States!</button>
</div>
</div>
<div id='map'></div>
<script>
$(function(){
function getStates() {
session
.run(districtQuery)
.then(function(result){
result.records.forEach(function(record) {
drawPolygons(parseWKTPolygons(record.get("wkt")),
record.get("text"));
});
})
}
</script>
</body>
</html>
I get the error saying :
Uncaught TypeError: $.getStates is not a function
at HTMLButtonElement.onclick (index.html:51)
$(function () { })
This is telling the interpreter to run any JavaScript/jQuery code as soon as the page is ready. This are usually referred to as an onready function. You don't typically create other functions inside of here.
Remove:
$(function () { })
Also, the way you are creating the onclick event is wrong. Use getStates() instead of $.getStates()
So all in all, your code should be changed as following:
<button onclick="getStates();">Load States!</button>
<script>
function getStates() {
session
.run(districtQuery)
.then(function(result){
result.records.forEach(function(record)
{
drawPolygons(parseWKTPolygons(record.get("wkt")),
record.get("text"));
});
});
}
</script>
Another way you could fix it is to leave your onready function and create the click event inside. Your getStates() function still needs to be placed outside of the onready function though and you would remove the onclick from the button element.
For example:
<button>Load States!</button>
<script>
$(function() {
$('button').click(function () {
getStates();
});
});
function getStates() {
session
.run(districtQuery)
.then(function(result){
result.records.forEach(function(record) {
drawPolygons(parseWKTPolygons(record.get("wkt")),
record.get("text"));
});
})
}
</script>
Now if you have more than one button on this page, you will need to add an ID or class to distinguish them. Then you'd replace $('button') with for example: $('#load_states_button) if using an ID or $('.button_class') if using a class.
These all produce the same result, so how to do it is just a matter of personal preference.
Hope this helped! Let me know if you have any questions. :)
You could add an id to the button and use something like this:
<button id="load-states">Load States!</button>
Javascript:
$(function() {
function getStates() {
session
.run(districtQuery)
.then(function(result){
result.records.forEach(function(record) {
drawPolygons(parseWKTPolygons(record.get("wkt")),record.get("text"));
});
})
}
// Adding event onClick to button
$('#load-states').on('click', getStates);
});
You can make the function global:
window.getStates = function getStates() {
...
};
Then you can simply use getStates() in the onclick attribute.
Of course, the cleaner way to do this would be to bind the event from JavaScript itself, using jQuery's $.click(). This would require you to add an id attribute to the button tag, or some other way to identify it from jQuery.
Take the function out of $(function() { ... }), because functions called from onclick have to be in the global scope. And call it as getStates(), not $.getStates()
<script>
function getStates() {
session
.run(districtQuery)
.then(function(result){
result.records.forEach(function(record) {
drawPolygons(parseWKTPolygons(record.get("wkt")),
record.get("text"));
});
})
}
</script>
This question already has answers here:
Event handler not working on dynamic content [duplicate]
(2 answers)
Closed 7 years ago.
I used the following codes to create a "New button" next to the "button". But, when I click the "New button", it cannot create another "New button". Why? I have defined the "click" event of "button" tag
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("body").append("<button type=button>New button</button>");
})
})
</script>
</head>
<body>
<button type="button">button</button>
</body>
Use event delegation for binding events automatically on dynamically added elements.
$(document).ready(function() {
var button = "<button type=button>New button</button>";
$(document).on('click', "button", function() {
$("body").append(button);
});
});
$(document).on('click', "button", function() {
$("body").append("<button type=button>New button</button>");
})
I have a problem.After adding a new element in the DOM, the element does not recognize old script and the same function that was in this document, how to solve this problem? how to reload the script
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div id='content'>Content.....</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script src='js/script.js' type='text/javascript'></script>
</body>
</html>
// script.js //
$('#content').click(function(){
$('body').append('<div id="apended">Click me!</div>');
});
$('#apended').click(function(){
alert('click!');
});
When you use .on('click', function (e) {}) function, it works only for existing elements. To handle click event on all selector elements, even for elements which will be added in future, you can use one of these functions:
$(document).on('click', "#appended", function (e) {
// some code code
alert('click!');
});
or:
$("body").delegate("#appended", "click", function () {
// your code goes here
alert('click!');
});
For more information read article about Understanding Event Delegation
Instead of click function You can use :
1.live(old version)
2.delegate
3.on
But , if you want to use click with immutation of delegate function :
var myFn=function(e){
if(e.target.id=='apended'){
alert('click');
}
}
$(document).click(myFn)
Demo :http://jsfiddle.net/abdennour/7cyjV/
Can someone tell me why the following is not working?
<head>
<script language="javascript" src="/assets/js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$("button").bind("click", function() {
alert("You clicked " + $(this).attr("id"));
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<button id="button1">Click Me!</button> <button id="button2">Click Me!</button> <button id="button3">Click Me!</button> <button id="button4">Click Me!</button> <button id="button5">Click Me!</button>
</body>
Nothing is happening when I click on any of the buttons.
Dave
Try:
$(document).ready(function() {
$("button").bind("click", function() {
alert("You clicked " + $(this).attr("id"));
});
});
Edit:
As stated by Alex Sexton, the use of live instead of bind is also preferable when you have to apply the same function to more than 2 elements of the same type.
Follow the link for more infos, credits to him.
You need to bind the click handler when the DOM is ready:
$(function() {
$("button").bind("click", function() {
alert("You clicked " + $(this).attr("id"));
});
});
Another solution would be to use event delegation, so it doesn't matter that the buttons don't exist yet.
$("button").live("click", function() {
alert("You clicked " + $(this).attr("id"));
});
Because your javasript code is executed before html body is loaded. You should call your JS after html is fully loaded. You can do it so:
$(function() { // it's called when document loads
$("button").bind("click", function() {
alert("You clicked " + $(this).attr("id"));
});
});
But it's good practice not to inject your code into global scope. You can do it so:
(function() { // it helps you not to inject your code into global scope
$(function() { // it's called when document loads
$("button").bind("click", function() {
alert("You clicked " + $(this).attr("id"));
});
});
})();