On click event doesnt work after element dynamically created - javascript

I use this for click event of button
$(document).on("click", "#feed_show_more_button", function() {
var a = $("#feed_show_more_button").attr("name");
show_more(a);
});
Then after button dynamically created i want to use this as a fake click
$("#feed_show_more_button").click();
but it doesnt work.
EDIT: I realized that show_more function doesnt fired unless it is included the ajax result. How can i make this function sth like global ?

Instead of fake call:
$("#feed_show_more_button").click();
you could simply write:
show_more( $("#feed_show_more_button").attr("name") );
If show_more is accessible(visible on scope) of course.

I am suspecting the diagnosis because the console logs "foo my button" when I paste this code into the javascript console (firebug)
$(document).on("click", "#feed_show_more_button", function() {
var a = $("#feed_show_more_button").attr("name");
console.log("foo",a)
//show_more(a);
});
$("body").html("<div name='my button' id='feed_show_more_button' style='border:1px solid red;height:100px;width:100px'></div>");
$("#feed_show_more_button").click()
Neat trick btw.

Related

Dynamic page navigation - custom event isn't triggered

I've created simple button:
<button type="button" class="btn btn-success link-accept" data-id="16">Accept</button>
with corresponding listener:
$(document).ready(function() {
$('.link-accept').on('click', function(event){
console.log('accepted');
});
});
Everything works okay.
Then I introduced AJAX-based dynamic (refreshless, you name it) navigation on my page using this function:
function ajaxLoadContent(pageurl){
$('#content').addClass("grey");
$.ajax({url:pageurl+'?rel=tab',success: function(data){
var title=$(data).filter('title').text();
var keywords=$(data).filter('meta[name=keywords]').attr('content');
var description=$(data).filter('meta[name=description]').attr('content');
var mdlTitle=$(data).find('.mdl-layout-title').html();
var content=$(data).find('#content').html();
var scripts=$(data).filter('#scripts').html();
document.title = title;
$('meta[name=keywords]').attr('content', keywords);
$('meta[name=description]').attr('content', description);
$('.mdl-layout-title').html(mdlTitle);
$('#content').html(content);
$('#scripts').html(scripts);
$('#content').removeClass("grey");
window.scrollTo(0, 0);
$(document).trigger("content-refreshed");
console.log('triggered content-refresh');
}});
}
And now my listener isn't working. I guess it's something about that dynamic refresh.
I've tried:
Listening to content-refreshed event - it fires, but isn't caught by my listener inside dynamically loaded page
Moved content of my $(document).ready anonymous function to separete function and called it at the bottom of the page - function is not defined.
Extracted content of my $('.link-accept').on('click') to separate function and called it with <button onclick="function()"> - function is not defined
I'm out of ideas now... It looks like it doesn't execute that code at all if loaded dynamically. What should I do? I guess eval is not an option here...
EDIT
I'm sure that dynamically loaded javascript isn't ran at all. Pure console.log at the top of <script> section doesn't work either. So I guess my primary task is to evaluate that code first - then it should work just right.
Change first snippet to:
$(document).on('click', '.link-accept', function(event){
console.log('accepted');
});
It will work then.
Otherwise it will just search for all .link-accept items first and then attach the handler once to the found objects. Nothing will update after your ajax request.
In my code snippets it is more dynamic. It binds the click to the document. If you click on any object on the document it will check if it is a .link-accept element. More dynamic and better performance.

append onclick function to div jquery

I'm trying to add an on click function to a div using these lines of code but the click event doesnt trigger the alert.
var str="<script>$(this).on(\"click\",function(){alert('hello');})";
str+="<";
str+="/script>";
$("div:contains('Send')").last().append(str);
I've also tried this and $(this)[0] but these give me the error this.on/ $(this)[0].on is not a function
I don't know what Im doing wrong and would appreciate any and all help on the matter.
Shouldn't have to go through the trouble of creating strings for script. You can just use jquerys .on and register it with a click event.
$("div:contains('Send')").last().on("click", function () {
alert('hello');
})
If you are using jQuery, you can add click event to all the div by using $("div") for selector (just remember to call the function after you load the div)
I have create an example of simple click function
$(".start").click(function() {
$(this).toggleClass("onClick");
})
http://jsfiddle.net/7j6s2Lws/2/
The $(this) will identify which object is actually trigger the event, and choose it only. In my case, if you click on a div, it will change color (of it and only it)
i would choose a slightly different approach. i hope i understood your problem right even though i dont really get what you want to achieve by putting <script> into your string here... maybe this helps:
html
<div id='container'>
<button>Send</button>
</div>
js
var $container = $("div:contains('Send')");
var elementToAppend = "<div class='myClass' style='width:100px; height:100px; border: 1px solid red'>added dynamically ... click me</div>";
appendToContainer($container, elementToAppend);
$('.myClass').click(function($element) {
alert(123);
});
function appendToContainer($container, element) {
$container.append(element);
}
fiddle
http://jsfiddle.net/2pofLnb7/2/

How to associate onClick with a dynamically generated div with dojo?

I am using dojo 1.9.2, and is trying to attach an onClick function on a piece of HTML code that I created on the fly, like this:
clickableDiv = "<div data-dojo-attach-point=\"testBtn\">Click Me!</div>";
self.racks.innerHTML = clickableDiv;
and then I want to give it an onClick function after, so right below the code I putted:
connect(this.testBtn, "onclick", alert("You Clicked It!"));
For some reason not only this wont work, when I refresh the page the alert "You Clicked It!" would pop up without me clicking anything...
I Have to use this dojo version, it's part of the requirement...
Any idea or suggestion on how I can go about doing this?
Well, dojo is part of javascript, so you can probably use some javascript function, for example:
clickableDiv = "<div id=\"testBtn\">Click Me!</div>";
self.racks.innerHTML = clickableDiv;
document.getElementById('testBtn').onclick=function(){alert("You Clicked It!");};
The code mentioned in the question is correct, except for one mistake. The "onclick" event needs a handler function, not the code directly. So, enclose that alert statement by a function.
connect(this.testBtn, "onclick", function(){alert("You Clicked It!")});
Or a separate function elsewhere can be linked here a handle by passing the function or just name of the function.
function abcd() {
alert('You clicked It');
}
connect(this.testBtn, "onclick", "abcd");//same as connect(this.testBtn, "onclick", abcd);
When providing an event handler (or a callback in general), you have to provide the function as reference. When you use:
connect(this.testBtn, "onclick", alert("You Clicked It!"));
You're actually saying that you want to connect the onClick event handler to the return value of that alert(). What you actually want is like the other answers already explained by wrapping it inside a function that is passed through by reference:
connect(this.testBtn, "onclick", function() {
alert("You Clicked It!")
});
However, since you're using data-dojo-attach-point which is generally used in widgets, you could also define your event handler in a similar way, for example:
clickableDiv = "<div data-dojo-attach-point=\"testBtn\" data-dojo-attach-event=\"onClick: myClickHandler\">Click Me!</div>";
Then you can just write a function called myClickHandler in your widget that shows the alert, for example:
myClickHandler: function() {
alert("You Clicked It!");
}
He's using dojo 1.9.2. connect is deprecated and he should be using on:
on(this.testBtn, "click", function(){
alert("You Clicked It!")
});
Your data-dojo-attach-point won't get picked up in dynamically placed HTML. You would put that in a custom widget template to provide the actual reference to your node/widget. If you did have that element in a template to begin with, you could simply use the attribute on your element:
data-dojo-attach-event="onClick: someFunction"

trigger('click') doesn't work on anchors without an actuall link in the href ( js function in the href attrbute )

i have some links for confirming comments
<a class="confirm_btn" href="javascript:confirm_ajax(17)" id="confirm_17">Confirm</a>
<a class="confirm_btn" href="javascript:confirm_ajax(20)" id="confirm_20">Confirm</a>
i want to be able to confirm all at once with one click , i know it's probably better to get all ids in an array and send them with one ajax call to backend script but for some reason i prefer not to do that and click each button .
here is my jq code
function confirm_all(){
$('.confirm_btn').each(function(index, element) {
$(this).trigger('click');
// also i've tried $(this).click();
console.log($(this).attr('id'));
});
}
when i run this i get the console.log result
confirm_17
confirm_20
confirm_22
confirm_33
confirm_34
but the click part doesn't work , it suppose to fire confirm_ajax function ... no error in the firebug .... if i click on the buttons they work fine
trigger('click') will only invoke attached event handlers; if you have JavaScript hrefs, they won't be triggered.
You could try attaching regular click handlers to your links, or you could do something like this instead:
var idFormat = /confirm_(\d+)/;
$('.confirm_btn').each(function() {
var btn = $(this);
var id = parseInt(idFormat.exec(btn.attr('id'))[1], 10);
confirm_ajax(id);
});

JQuery - What can I do to make this work?

http://jsfiddle.net/piezack/X8D4M/5/
I need the change created by clicking the button to be detected. At the moment you have to click inside the field and then outside for it to detect any change.
Thanks guys.
The code for the button CANNOT be altered. Good tries so far though.
Was overcomplicating things. Answer http://jsfiddle.net/piezack/X8D4M/56/
Example using trigger:
//waits till the document is ready
$(document).ready(function() {
$('button.butter').click(function() {
var $form6 = $('#FormCustomObject6Name');
$form6.val('Text has changed');
$form6.trigger('change')
});
$('#FormCustomObject6Name').change(function() {
var x = $('#FormCustomObject6Id').val();
$("a").filter(function() {
return this.href = 'http://www.msn.com'
}).attr('href', 'http://www.google.com/search?q=' + x);
alert(x);
});
});
i think that jmar has the right idea...if i understand correctly you want to be able to type whatever in the box and without clicking out of it to have the button change it to the text has changed.
i dont know if that alert is really necessary, but you can do this if the alert is not needed:
http://jsfiddle.net/X8D4M/24/
To trigger the change event simply add a .trigger after setting the value.
Also, you're selector for the link wasn't working so I just changed it to #link.
http://jsfiddle.net/X8D4M/22/

Categories