In the example below
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
test
<button id="btn-add">Add</button>
<div id="placeholder">
</div>
<script type="text/javascript">
$(document).ready(function () {
$('a').on('click', function () {
alert('clicked');
});
$("#btn-add").on("click", function () {
$('#placeholder').prepend('<a href=\'#\'>blah2</a>');
});
});
</script>
</body>
</html>
If you click on 'Add' then 'blah2' nothing happens even though I am trying to alert on any anchor click. As a check if you click on 'test'you get the popup
Try this instead:
$('body').on("click", "a", function () {
alert('clicked');
});
Link to fiddle
Since the element is generated dynamically, you need to use delegation with the on() method or create a literal jQuery object and add a click event.
$('closestParent').on('click', 'a', function(){ ... })
// OR
var $link = $('<a href=\'#\'>blah2</a>').click(function(){ ... })
$link.prependTo('#placeholder')
Its because you need to delegate the click to a parent element. If you are using 1.7+ use .on or if you are using 1.6 and lower you can use .delegate(). The element doesn't exist when the dom is ready so you need to delegate the event to a parent element. Meaning you can use $(document) or use any parent element that is already there
$(document).on("click","a", function () { //<-- this allows for the event to bubble up to the document in this case
alert('clicked');
});
$(document).delegate("a","click", function () {
alert('clicked');
});
Related
I can successfully bind an event to dynamically added elements, but I have a problem triggering it on its first load programmatically.
$('body').on('change', '#elem', function () {
console.log('bind event success');
});
I tried these codes below but do not work.
Not working
$('body').trigger('change');
Not working
$('body').on('change', '#elem', function () {
console.log('hello world');
}).change();
You can trigger an event on the DOM element #elem directly, as you can see here:
$('body').on('change', '#elem', function () {
console.log('new value is: '+this.value);
});
$("button").click(function(){$("#elem").val("3").change()})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="elem"><option>1</option><option>2</option><option>3</option></select>
<button>trigger change to 3</button>
I have this piece of code
window.onload = function () {
$('#btnFilter').click(function (e) {
btnFilter(e);
});
}
The function works on button click but I need that the button is clicked when the page opens. I've tried things like $('#btnFilter').trigger( "click" ); but the button still not clicked on page opening. How can I achieve this thing? I can't just call the function because I get the error "Cannot read property 'currentTarget' of undefined" beacuse I don't give any event as parameter.
function btnFilter(e) {
element = e.currentTarget.parentElement;
//other code
}
You can try like this:
$(document).ready(function(){
$('#btnFilter').trigger('click');
});
$(document).on('click','#btnFilter',function(e){
btnFilter(e);
});
function btnFilter(e)
{
element = e.currentTarget.parentElement;
}
You can change your 'btnFilter' to accept the button instead of the event:
function btnFilter(element) {
element = element.parentElement;
...
}
$(function() {
$("#btnFilter").click(function(e) { btnFilter(this); return false; });
// Pass the button to the filter operation on load
btnFilter($("#btnFilter")[0]);
});
alternatively, accept the parent element directly
$(function() {
$("#btnFilter").click(function(e) { btnFilter(this.parentElement); return false; });
// Pass the button parent to the filter operation on load
btnFilter($("#btnFilter")[0].parentElement);
});
If you use jquery i would keep it coherent and not mix it with vanilla javascript. A Jquery solution is:
$(document).on("click", "#btnFilter", btnFilter);
$(document).ready(function(){$("#btnFilter").click()});
or
$(document).on("click", "#btnFilter", btnFilter);
$(document).ready(btnFilter);
In you solution the error is the event binding: when you bind the event to #btnFilter on page load, the element is not existing yet, so the function cannot be triggered.
jQuery Solution:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").trigger("click");
});
</script>
</head>
<body>
<button onclick="alert('clicked')">Click</button>
</body>
</html>
I am trying to change the class of a div element and write click function for class names.
on clicking 'editthis' I am logging 'editthis' and removing the class 'editthis' and adding the class 'savethis'
I have click function for class 'savethis' but this click event is not executed it logs 'editthis' always, but the class name changed to 'savethis', but the click function on 'savethis' is not executed
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(function(){
$('.editthis').on('click', function(){
console.log('editthis');
$(this).text('SAVE');
$(this).removeClass('editthis');
$(this).addClass('savethis');
});
$('.savethis').on('click', function(){
console.log('savethis');
$(this).text('EDIT');
$(this).removeClass('savethis');
$(this).addClass('editthis');
});
});
</script>
<div class="editthis">EDIT</div>
if it is not clear please ask I will try to provide more details.
Delegate the event handling to a parent element.
$(function(){
$(document).on('click', '.editthis', function(){
console.log('editthis');
$(this).text('SAVE');
$(this).removeClass('editthis');
$(this).addClass('savethis');
}).on('click', '.savethis', function(){
console.log('savethis');
$(this).text('EDIT');
$(this).removeClass('savethis');
$(this).addClass('editthis');
});
});
The document i put would work, but it is best to delegate to a parent closer to the button.
Try this way:
<script>
$(function(){
$(document).on('click','.editthis', function(){
console.log('editthis');
$(this).text('SAVE');
$(this).removeClass('editthis');
$(this).addClass('savethis');
});
$(document).on('click','.savethis', function(){
console.log('savethis');
$(this).text('EDIT');
$(this).removeClass('savethis');
$(this).addClass('editthis');
});
});
</script>
I have this simple HTML code:
<div id="new_gallery">
<p id="add_gallery">Add new gallery</p>
</div>
and jQuery code:
<script>
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" />Add');
$(this).remove();
});
$("#create_new_gallery").on('click', function(){
alert('1');
});
</script>
First function is working, but second one is not. I need to create new input element, send data via ajax, and then delete the input element and append a p element once again. How can I do this?
When the second statement runs, the element #create_new_gallery does not exist yet so it does nothing.
You can do the binding to the click event after you created the element for instance, this ensures the element exists in the DOM:
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name="new_gallery" />Add');
$(this).remove();
$("#create_new_gallery").on('click', function() {
alert('1');
});
});
DEMO
Here is a little bit more optimized version. It's a bit non-sense to append an element and have to re-query for it (event though querying by id is the fastest method. Besides, it's best to use the chaining capabilities of jQuery afterall:
$("#add_gallery").click(function() {
var $gallery = $("#new_gallery");
$('<input name="new_gallery" />').appendTo($gallery);
$('Add')
.on('click', function() {
alert('1');
})
.appendTo($gallery);
$(this).remove();
});
DEMO
#create_new_gallery doesn't exist when you bind its click event.
Here is what your code should look like:
$("#add_gallery").click(function() {
var newG = $("#new_gallery");
$('<input name"new_gallery" />').appendTo(newG);
$('Add').appendTo(newG).on('click',
function() {
alert('1');
});
$(this).remove();
});
Notice that getting $("#new_gallery") into a variable avoid to look for it twice.
$(document).ready(function () {
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" />Add');
$(this).remove();
$("#create_new_gallery").on('click', function(){
alert('1');
});
});
});
DEMO: http://jsfiddle.net/39E4s/2/
Try live to handle the events fired for elements added after the page has loaded.
$("#create_new_gallery").live('click', function(){
alert('1');
});
http://api.jquery.com/live/
I've got code so that when you click on a word, it is replaced by another word.
<script>
$(document).ready(function() {
$('.note_text').click(function(){
$(this).remove();
$('#note_div').append('<span class="note_text">new</span>');
// re-applying behaviour code here
});
});
</script>
<div id="note_div">
<span class="note_text">preparing</span>
</div>
I need the appended word to have the same click behaviour. What is the best way to do this?
change
$('.note_text').click(function(){
to
$('.note_text').live('click',function(){
This will cause anything on your page that ever gets the class 'note_text' to have the behaviour set by .live
You should use a .live()help or .delegate()help binding for that purpose.
$(function() {
$('#note_div').delegate('.note_text', 'click', function(e) {
$(e.target).parent().append("<span class='note_text'>new</span>").end().remove();
});
});
Demo: http://www.jsfiddle.net/PkngP/2/
You could rebind the handler:
function handler(){
$(this).remove();
$('#note_div').append("<span class="note_text">new</span>");
$(".note_text").unbind("click");
$('.note_text').click(handler);
}
$(document).ready(function() {
$('.note_text').click(handler);
});