Javascript function after html appended - javascript

I have a problem with my javascript function :
$(".like-btn").click(function () { .. }
this function is not triggered anymore after in my javascript somewhere else I do stuff like
$("#1021").append("'<button type="submit" class="btn btn-default like-btn" ... .etc ");
So basically I need my jquery to be triggered also after I add some more html on my page.

Since the like-btn class is added dynamically, you need to use event delegation to register the event handler like this:
// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#1021').on('click', '.like-btn', function(event) {
event.preventDefault();
alert('testlink');
});

Related

How to prevent jQuery duplicate function being called

I have a jQuery on('click') function like this:
function enabled_click() {
$('.btn_enabled').on('click', function() {
alert('CLICKED');
});
}
and then I have another post function like this
$(document).on('click', '.btn_add_link', function(e) {
var url = 'www.xxx.my-function';
post_data(url, function(data) {
if (data.status == 'success') {
$('#my_wrapper').append(data.response);
enabled_click();
} else {
alert('error');
}
});
return false;
});
The post function will append another .btn_enabled button. If i did not call the enabled_click() function on the success post, then the newly added .btn_enabled would not be able to trigger the onclick function.
But if I call the enabled_click() function like i did above, the already existing .btn_enable will then call the onclick function twice and alert CLICKED twice. Is there any way to make it so it only alerts once?
Event delegation by binding to a common parent, as answered by #qs1210, is a possible solution, and a very efficient one (because there's only one common handler instead of one per element). But depending on the code, it may require more changes.
As a compatible "drop-in replacment" just unbind the event handler before binding again. To achieve this in an easy and stable way, you can use jQuery's "namespace" feature for event names (see .on(), "Event names and namespaces"):
function enabled_click(){
$( '.btn_enabled' )
.off('click.some_namespace')
.on('click.some_namespace'), function() {
alert('CLICKED');
});
}
Note: if you extract the event handler into its own function and use that as second parameter to .off(), you could omit the namespace:
function click_handler(){
alert('CLICKED');
}
function enabled_click(){
$( '.btn_enabled' )
.off('click', click_handler)
.on('click', click_handler);
}
But this only works it the click_handler variable is "stable": depending where and when the click handler is defined, the variable (click_handler in this example) could be re-assigned and .off() couldn't detach the previous handler anymore.
Follow-up: in your example, you only apply the event handler to newly appended elements ($('#my_wrapper').append(data.response)). You could alter enabled_click to explicitly take the new element(s) as an argument:
function enabled_click($element){
$element.find('.btn_enabled' ).on('click', function() {
alert('CLICKED');
});
}
and call it like this:
var $newElement = $(data.response);
$('#my_wrapper').append($newElement);
enabled_click($newElement);
Now the event handler gets attached to new elements only, and not to already existing which have the event handler already attached.
(I'm using $ as prefix for all my variables holding jQuery collections, in order to distinguish them from pure DOM nodes)
Your can write like this
document.on('click', '.btn_enabled', function() {
alert('CLICKED');
})`
delegate event to dom, it makes everything harmony.

How to convert jQuery to JavaScript name attribute

I'm trying to find a way to create 'on click' events for dynamically generated buttons in JS. I know that in jQuery it can be done like this:
$(document).on('click', 'name=[buttonName]', function() {});
I know the e.target method in JS, but I'm wanting to find a way to do it with a name attribute instead.
Thanks
Firstly that line of jQuery isn't quite right as the square brackets are in the wrong place:
$(document).on('click', '[name="buttonName"]', func);
To achieve the same in plain JS you would need to attach a click event handler to a static parent element, then check the name property of the clicked element:
document.addEventListener('click', function(e) {
if (e.target.name == 'buttonName') {
// do something...
}
});
document.addEventListener('click', function(e) {
if (e.target.name == 'buttonName') {
alert('Hello!');
}
});
<button>I do nothing!</button>
<button name="buttonName">I say hello!</button>
You can use querySelector in a similar way than you would in jQuery, and attach the event listener whenever a new element is added to the DOM.
document.querySelector("button[name='buttonName']").addEventListener("click", function(){
alert("Hello, World");
});
<button name="buttonName">Click me</button>
The difference to the original jQuery code is that in that example it listens to events on the document whereas this does not.
You can use getElementByName to add click event to your button which is dynamically render
document.getElementByName("ButtonName").addEventListener("click", function(e) {
});

Trying to write a function from inline javascript

I've got some code from a developer that left our company. He wrote an inline function looking like this:
<button class="xxx" id="MyID" type="button" onclick="javascript: $('#openThis').slideToggle('slow');">btnText</button>
I've tried to remove this and put it in another function to write a callback so I can scroll to the toggled area when it's visible.
$("#MyID").click(function () {
$("#openThis").slideToggle("slow");
});
But I can't seem to get it to work. What am I doing wrong?
are you adding the listener before or after the object is created on the DOM?
because if you are trying to bind that onclick function without waiting the document to be ready theres no object to create the listener.
something like this could work:
$(document).on('ready', function() {
$("#MyID").click(function () {
$("#openThis").slideToggle("slow");
});
});
If you button is added dynamically then use on instead of click
Attach an event handler function for one or more events to the
selected elements.
Event handlers are bound only to the currently selected elements; they
must exist at the time your code makes the call to .on()
//Instead of document you can use a container id
$(document).on('click',"#MyID",function () {
$("#openThis").slideToggle("slow");
});
What this approach does is it adds event to a currently selected element which is document here and it will delegate the event to your selector which is #MyID in this case.
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time.
$(document).on('click', '#myBtn', function(){
$('#foo').slideToggle('slow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="foo">content</div>
<button id="myBtn">Click me</button>
You want to scroll to the area so remove the JavaScript from the button
You need to do something like this
$("#MyID").click(function() {
$('html, body').animate({
scrollTop: $("#openThis").offset().top
}, 2000);
$("#openThis").slideToggle("slow");
});
You should delete the onclick="" attributes in the button tag and in your javascript :
$("#MyID").click(function (e) {
e.preventDefault();
$("#openThis").slideToggle("slow");
});
Use the prevent default.
Hope that help

Event call multiple time after ajax replace element

I have an problem with Jquery event. Jquery Event was call multiple time after I replace that element with another element but same type and same id.
// 1. ajax call success and replace my block
// 2. This is my event that I want it happen.
$(document).on("click", ".polaroid button.addImage", function(event) {
event.preventDefault();
// trigger browse file to upload
$(event.target).closest("div.polaroid").find("input[type=file]").trigger("click");
});
This code was used to resold event was call after AJAX success. So, why is button.addImage with event click called many times at the same time AJAX is called?
This is html:
<div class="col-md-3 polaroid">
<img src="images/ingredient/default_img.png" title="Main image" />
<input type="file" name="file-image" style="display:none"/>
<button type="button" data-toggle="tooltip" title="Add" class="btn addImage"><i class="glyphicon glyphicon-plus icon-plus"></i></button>
</div>
You most likely are loading this script again or calling a function that adds this event handler again
The best fix is to find where this event handler is being called again.
A workaround would be to namespace the event and always remove the event handler using off() before adding it again
$(document)
.off('click.polaroid')
.on("click.polaroid", ".polaroid button.addImage", function(event) {
// other code
});
use one()
$(document).one("click", ".polaroid button.addImage", function(event) {
Thanks. I found answer. that is use "off" before "on", like this:
I update the answer of Mr.charlietfl.
$(document)
.off('click',".polaroid button.addImage")
.on("click", ".polaroid button.addImage", function(event) {
event.PreventDefault();
// other code
});

Adding onClick event dynamically using jQuery

Due to a plugin being used, I can't add the "onClick" attribute to the HTML form inputs like usual.
A plugin is handling the forms part in my site and it doesn't give an option to do this automatically.
Basically I have this input:
<input type="text" id="bfCaptchaEntry" name="bfCaptchaEntry" style="">
I want to add an onClick to it with jQuery onload for it to be like this:
<input onClick="myfunction()" type="text" id="bfCaptchaEntry" name="bfCaptchaEntry" style="">
How do I go about doing this?
I know this might not be standard practice but seems like the easiest option to do in my situation.
I'm a newbie to jQuery so any help is very much appreciated.
You can use the click event and call your function or move your logic into the handler:
$("#bfCaptchaEntry").click(function(){ myFunction(); });
You can use the click event and set your function as the handler:
$("#bfCaptchaEntry").click(myFunction);
.click()
Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
http://api.jquery.com/click/
You can use the on event bound to "click" and call your function or move your logic into the handler:
$("#bfCaptchaEntry").on("click", function(){ myFunction(); });
You can use the on event bound to "click" and set your function as the handler:
$("#bfCaptchaEntry").on("click", myFunction);
.on()
Attach an event handler function for one or more events to the
selected elements.
http://api.jquery.com/on/
try this approach if you know your object client name ( it is not important that it is Button or TextBox )
$('#ButtonName').removeAttr('onclick');
$('#ButtonName').attr('onClick', 'FunctionName(this);');
try this ones if you want add onClick event to a server object with JQuery
$('#' + '<%= ButtonName.ClientID %>').removeAttr('onclick');
$('#' + '<%= ButtonName.ClientID %>').attr('onClick', 'FunctionName(this);');
Try below approach,
$('#bfCaptchaEntry').on('click', myfunction);
or in case jQuery is not an absolute necessaity then try below,
document.getElementById('bfCaptchaEntry').onclick = myfunction;
However the above method has few drawbacks as it set onclick as a property rather than being registered as handler...
Read more on this post https://stackoverflow.com/a/6348597/297641
$("#bfCaptchaEntry").click(function(){
myFunction();
});
Or you can use an arrow function to define it:
$(document).ready(() => {
$('#bfCaptchaEntry').click(()=>{
});
});
For better browser support:
$(document).ready(function() {
$('#bfCaptchaEntry').click(function (){
});
});
let a = $("<a>bfCaptchaEntry</a>");
a.attr("onClick", "function(" + someParameter+ ")");
as #Selvakumar Arumugam suggested, but the function call on registering also
$('#bfCaptchaEntry').on('click', myfunction);,
rather than use
$('#bfCaptchaEntry').on('click', () => { myfunction});

Categories

Resources