Set onclick handler to dynamically created button - javascript

I need to create button dynamically and assign its onclick handler. Click handler could be anonymous function (I'm not sure how it is called in JS). It is allowed to jQuery.
I tried something like this:
<div>
<button id="x">Show</button>
</div>
function magick() {
console.log('some special magick');
}
function createButton(itsHandler) {
var guts = '<button id="__internal" onclick="'
+ itsHandler + // <-- that's wrong
'">Test</button>';
$($.trim(guts)).appendTo('body');
}
$(document).ready(function () {
$("#x").bind("click", function() {
createButton(magick);
});
});
but is doesn't work.
(Here is jsfiddled code)
How it can be accomplished?
UPD1: It would be better if it was done inside of the createButton function.

Try to use on() like
$('body').on('click','#__internal',function(){
console.log('test some special magick');
});
$(document).ready(function () {
$("#x").bind("click", function() {
var guts = '<button id="__internal" >Test</button>';
$($.trim(guts)).appendTo('body');
});
});
Demo
Updated In your code, below two lines can create magic for you like,
var guts = '<button id="__internal">Test</button>';
$($.trim(guts)).appendTo('body').bind('click', magick);
Demo 1

try using on:
see FIDDLE
$("body").on("click", "#__internal", function(){
alert('some special magick');
});

I think you can do it that way just make onclick value a function call like this:
var guts = '<button id="__internal" onclick="magick()">Test</button>';
But it won't work in jsfiddle, because jsfiddle put your js code in window load handler so the magick function would not be visible outside that handler.
And about your createButton function you should pass the function's name instead of the function itself, try this:
function createButton(itsHandlerName) {
var guts = '<button id="__internal" onclick="'
+ itsHandlerName +
'()">Test</button>';//add () to the function's name
$($.trim(guts)).appendTo('body');
}
$(document).ready(function () {
$("#x").bind("click", function() {
createButton("magick");//pass function name
});
});

You may use on() for binding events on dynamically added elements. Like this:
$(document).on('click', '#__internal', function () {
alert('some special magick');
})
WORKING FIDDLE...

Related

How can I read ".on()" method arguments in jQuery?

I have no idea how to bite this problem. Below two examples are working great but I want to avoid the DRY problem.
parentElement.on('focusout', '.foo-class', function () {
// console.log('hello foo')
});
and:
parentElement.on('focusout', '.bar-class', function () {
// console.log('hello bar')
});
I would like to make it more universal. I have to deal with two classes while the parent stays the same.
Assuming that this is the first step:
parentElement.on('focusout', classValue, function () {
// How to display this class so I can call different stuff depending on the class value?
// console.log('hello ' + classValue)
});
May be something along these line, refined from guardio's solution.
Fiddle: https://jsfiddle.net/pvorhknv/2/
What it doing here is to get the element been called for the handler and accessing the attributes. You can use this element "this" for any such use.
$(document).on('focusout', 'input', callme);
function callme(){
console.log('hello ' + $(this).attr('class').split('-')[0])
}
UPDATE:
One other thing you can use it to mark data attribute for the elements.
Fiddle: https://jsfiddle.net/pvorhknv/3/
<input type='text' class='foo-class' data-classname="foo">
<input type='text' class='bar-class' data-classname="bar">
And hence you can access them,
function callme(){
console.log('hello ' + $(this).data('classname'));
}
To look if the (1) element has a particular class, and to (2) get all classes of $(this), see following:
parentElement.on('focusout', classValue, function () {
// (1). find out if element has class 'foo-class'
if $(this).hasClass('foo-class'){
// ...
}
// (2). for each class of element do something
$($(this).attr('class').split(' ')).each(function() {
if (this !== '') {
// ...
}
});
)};
You can use data attribute for specify event which you want to run. My solution is below (simple nothing more nothing less):
html
<div class="event" data-color-event="blue">click me = blue</div>
js
// one listener
$('body').on('click', '.event', function() {
var ev = $(this).data('color-event');
$('body')[ev]();
});
// event functions on demand
$.fn.blue = function() {
alert('blue');
}
$.fn.red = function() {
alert('red');
}
JSFIDDLE DEMO
Separate your classes with commas, and then check the class in the callback.
https://jsfiddle.net/guanzo/dmpgxxt0/
$('.container').on('click','.test1,.test2',function(){
console.log($(this).attr('class'))
})
Did you try
parentElement.on('focusout', '.foo-class, .bar-class', function () {
// console.log('hello foo')
});
And more:
parentElement
.on('focusout', '.foo-class, .bar-class', function () {
// console.log('hello foo')
})
.on('click', '.baz-class', function() { alert('xx'); })
;

Grab URL parameter onclick of url.. Jquery, Javascript

I am having some trouble trying to store the url parameters of some dynamic links that I created with an ajax post response. The ajax post is working correctly and the name and subgenre vars are being properly filled from the ajax response. Now what I would like to happen is that a user clicks on one of the generated urls, the parameters inside of the urls, i.e. subgenre="blah", are going to be sent to a database and stored. The problem I am having is that a standard event click function will not work inside or outside of the document ready function.
$(document).ready(function() {
$.each(data, function() {
$('#artist-suggestions').append('<li>' + this.name + this.new + '</li>');
});
});
I then created an onclick function, as below, but I can not use the "this" query because it is outside of the document scope. I had to put the onclick function outside of the document ready function or else it would not work.
function artistGen(){
alert('dfdsf');
};
What am I missing here or what am I doing wrong?
You can pass these in the onclick function when you make each element.
$(document).ready(function() {
$.each(data, function() {
artist = this.name;
$('#artist-suggestions').append('<li>' + this.name + this.new + '</li>');
});
})
;
function artistGen(Blah1, Blah2){
saveData(Blah1, Blah2);
alert('dfdsf');
};
In jQuery for dynamic elements you can use the click event in this way
$('#artist-suggestions li').on('click', 'a', function() {
// do something
});
or you can continue with the way you did, by using a function but just add a parameter to that function
like
function artistGen(Artist){
// do something
};
You need to remove the artistGen() function from the scope of the .load()
$(window).load(function(){
$('#artist-suggestions').append('<li>jim new</li>');
});
function artistGen(){
alert('dfdsf');
}
JSFIDDLE DEMO
That's just how it is a function called in those event attributes have to be defined globally(or defined right there) not in any wrapper function. A better solution would be to attach event handlers.
$(document).ready(function() {
function artistGen(){
alert(this.href);
};
$.each(data, function() {
var $li = $('<li>' + this.name + this.new + '</li>');
$li.find('a').on('click', artistGen);
$('#artist-suggestions').append($li)
});
});

Have the element who call my js function

I know my question have answer in the past but I don't have the vocabulary to find this.
I call a JavaScript function like this:
Voir +
This function change the state of the element .stats-table but I want to know which button have been clicked to call this function?
Better : can I have a jQuery object of this button?
Try to pass the this reference to know which button was clicked,
HTML:
Voir +
JS:
function showTable(selec,elem){
var currentElem = $(elem); //Clicked element
}
If you don't want to change the signature of the function and the way you invoke it (as others have suggested), you can use the global window.event to identify the clicked element:
function showTable(selector)
{
var clickedElement = window.event.target;
//...
}
See MDN.
When you use jQuery, you might consider refactor your code like this:
$(document).ready(function(){
$('.show-table-link').on('click', function(){
var $usedButton = $(this)
showTable('.stats-table')
}
})
Voir +
It's good practice to attach the on click handler instead of writing it inline. Further reading document.ready and jQuery event basics.
You can pass any value or id and your can identify the function
<script type="text/javascript">
function showTable(clss_name,fun_id)
{
if(fun_id=='A1')
{
alert("First function Executed");
}
if(fun_id=='A2')
{
alert("Second Function is executed");
}
}
</script>
......
......
......
Voir +
Voir2 +
If your function is like this:
function showTable(selec) {
// some code
}
You can get the clicked element like this, using this:
function showTable(selec) {
// some code
var clickedElem = this;
}

how to pass parameter in jquery using .on?

Good Day, this maybe a silly question :) how can I pass a parameter to an external javascript function using .on ?
view:
<script>
var attachedPo = 0;
$this.ready(function(){
$('.chckboxPo').on('ifChecked', addPoToBill(attachedPo));
$('.chckboxPo').on('ifUnchecked', removePoToBill(attachedPo ));
});
</script>
external script:
function addPoToBill(attachedPo){
attachedPo++;
}
function removePoToBill(attachedPo){
attachedPo--;
}
but Im getting an error! thanks for guiding :)
You need to wrap your handlers in anonymous functions:
$('.chckboxPo')
.on('ifChecked', function() {
addPoToBill(attachedPo);
})
.on('ifUnchecked', function() {
removePoToBill(attachedPo);
});
You can also chain the calls to on as they are being attached to the same element.
If your intention is to count how many boxes are checked, via passing variable indirectly to functions try using an object instead like this:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/pBkhX/
var attachedPo = {
count: 0
};
$(function () {
$('.chckboxPo')
.on('change', function () {
if ($(this).is(':checked')) {
addPoToBill(attachedPo);
} else {
removePoToBill(attachedPo);
}
$("#output").prepend("" + attachedPo.count + "<br/>");
});
});
function addPoToBill(attachedPo) {
attachedPo.count++;
}
function removePoToBill(attachedPo) {
attachedPo.count--;
}
If it is not doing anything else you can simplify the whole thing to count checked checkboxes:
$(function () {
var attachedPo = 0;
$('.chckboxPo')
.on('change', function () {
attachedPo = $(".chckboxPo:checked").length;
});
});
"DOM Ready" events:
you also needed to wrap it in a ready handler like this instead of what you have now:
$(function(){
...
});
*Note: $(function(){YOUR CODE HERE}); is just a shortcut for $(document).ready(function(){YOUR CODE HERE});
You can also do the "safer version" (that ensures a locally scoped $) like this:
jQuery(function($){
...
});
This works because jQuery passes a reference to itself through as the first parameter when your "on load" anonymous function is called.
There are other variations to avoid conflicts with other libraries (not very common as most modern libs know to leave $ to jQuery nowadays). Just look up jQuery.noConflict to find out more.

User-defined callback function is being fired multiple times in Javascript/jQuery

There are some similar questions, but they all seem like regarding native jQuery callback functions.
So I have this code which (live) creates a div containting some form elements.
Values of these elements should be retrieved inside a callback function when (before) the div is removed.
function popup(callback) {
// ...
// before removing the div
callback.call();
// remove div
}
Unexpectedly, the callback function is being fired multiple times (increasingly) after the first time popup is executed.
I have simplified the code, and here is the fiddle.
I hope this is what you need.
function popup(callback) {
$("body").append('<div><span id="test">test</span> close</div>');
$(document).on("click", "#close", function() {
callback.call();
//
//callback = function() {};
$(document).off("click", "#close");
$("div").remove();
});
};
$(document).on("click", "#open", function() {
popup(function() {
alert('$("#test").length = ' + $("#test").length);
});
});
Basically, you need to remove event handler by invoking off() method.
Try dynamically generating the elements instead of using a string. This will allow you to bind events easier.
function popup(callback)
{ var $elem = $("<div></div>");
$elem.append($("<span></span>").html("test"));
$elem.append(" ");
$elem.append($("<a></a>").html("close").attr("href", "#"));
$("body").append($elem);
$elem.find("a").click(function() {
callback.call();
$elem.remove();
});
};
$(document).on("click", "#open", function() {
popup(function() {
alert('$("#test").length = ' + $("#test").length);
});
});
Example: http://jsfiddle.net/4se7M/2/
I don't know the exact scenario, but why do you want to bind and unbind the event each time you show the popup?
You can bind only once, like this, can't you?
$(document).on("click", "#close", function() {
alert('$("#test").length = ' + $("#test").length);
$("div").remove();
});
function popup() {
$("body").append('<div><span id="test">test</span> close</div>');
};
$(document).on("click", "#open", function() {
popup();
});

Categories

Resources