adding onclick event on replace with jquery - javascript

I'm having a problem on putting onclick event on a replaceWith on jquery. My function on the 2nd onclick event is not functioning. This is my sample code.
sample.html
<div id = "first_div" onClick = "replace()">First</div>
my.js
function replace() {
$('#first_div').replaceWith("<div id = 'sec_div' onclick='flyout('fb')'>Second</div>");
}
When I click the first_div it works. It shows the 2nd_div, but when I click the 2nd div it doesn't do anything.
function flyout(data){
if (data == "fb") $('#sec_div').replaceWith("<div>Last</div>");
}

The reason your code doesn't work is that you're not passing a function to the 'onclick' of the #sec_div element. You have it defined as onclick="flyout('fb');", but the flyout function doesn't return anything. I changed the code below so that flyout returns a function and encapsulates the value of data in its closure, in case you want to use this same function with different values for the data parameter.
Also, I have a provided a solution which helps to separate your HTML from your Javascript. Using jquery you can accomplish that by using the delegate method to bind a function to any event.
HTML:
<div id="first_div">First</div>
JS:
$("body").delegate('#first_div', 'click', replace);
$("body").delegate('#sec_div', 'click', flyout("fb"));
// change replace to:
function replace() {
$(this).replaceWith("<div id='sec_div'>Second</div>");
}
// change flyout to:
function flyout(data){
return (function(){
if (data == "fb") {
$(this).replaceWith("<div>Last</div>");
}
});
}
EDIT:
According to the latest jquery documentation use of the live method is deprecated, use delegate instead.

There is no click event bound to the new div.
Either add a new listener after the replaceWith() call or else use live() to listen at the document level.

You haven't escaped it properly in the function replace. The
onclick='flyout('fb')'
part has three four single quotes. the second quote closes the first quote and the third quote starts a new string. Try escaping it as follows
element="<div id = 'sec_div' onclick='flyout(\"fb\")'>Second</div>"
$('#first_div').replaceWith(element);
Also checkout http://jsfiddle.net/5Stuh/

Related

Why does this equivalent of "on.("click", function) [..]" automatically fires a click even when written in pure JavaScript?

This code:
var el = $(".threeLines");
el.on("click", function(){
$(this).toggleClass("active");
});
Helps me add the class "active" on a click event to create a nice effect on a menu icon, like this:
I rewritten the code to pure JS as below:
function test_xz(s) {
s.classList.add("active")
}
var el_container = document.getElementsByClassName("threeLines")[0];
el_container.addEventListener("click", test_xz(el_container));
But it instantly fires when the document is ready and it completely messes up like this:
I understand that jQuery's "$" corresponds to querySelector, but I also tried that and it didn't work.
After a bit of research (removing every other function that could be related, logging everything) I concluded that the problematic line is the addEventListener itself, I wrote:
el_container.addEventListener("click", console.log("Hey!"));
and it would just log "Hey!" on page-load.
How can I make this work?
In the below line you are calling the method test_xz with an argument.
el_container.addEventListener("click", test_xz(el_container));
Instead, change to the following (without changing the function definition of test_xz) :
el_container.addEventListener("click", function(){
test_xz (el_container);
});
To toggle the active class:
function test_xz(s) {
s.classList.toggle("active");
}
In your question, you mentioned jQuery's "$" corresponds to querySelector and I think it's no. $ is just another name (alias) for jQuery and what goes inside the () after $ is a selector.
el_container.addEventListener("click", test_xz(el_container));
You're calling text_xz(). That's why the handler is executing. It is for the same reason that passing console.log("Hey!") logs that string to the console.
To pass the handler on its own without calling it, simply pass the handler name:
el_container.addEventListener("click", test_xz);
In addition, you incorrectly ported toggleClass() to classList.add() and not classList.toggle():
function test_xz(s) {
s.classList.toggle("active")
}

How can I pass an object value name to a function in Jquery

I'm working with the JQuery Simple modal plugin and I would like to pass a Freemarker variable/object on the click of a link to my Jquery function.
As a test, I created an alert box to see if the value is being passed and it doesn't seem to work.
$(function() {
// Load dialog on page load
//$('#basic-modal-content').modal();
// Load dialog on click
$('#hey').click(function myName(uid) {
var x = uid;
alert(uid);
return false;
});
});
HTML
<div id="disclaimer${item.uid}">
Modal data
</div>
<a onclick="myName('${item.uid}')" id="hey">Read the blog</a>
The alert box just comes up as a blank object. Any help would be appreciated. Thanks!
First off, you look like you are confusing the html onclick attribute with the jquery .click method.
<a onclick="myName('${item.uid}')" id="hey">Read the blog</a>
This will call a javascript function named "myName" and pass it a the string ${item.uid}. Note, this is a string because you wrapped it in single quotes. If you do an alert, your alert will literally say "${item.uid}".
Then you have a jquery bind event for click:
$('#hey').click({....
Ok, you need to pick one. Either use the onclick to call a javascript function or use the bind click event. Both methods can work (I prefer javascript onclick functions myself but that is just opinion).
If you want to use the jQuery bind, put a debugger; line in it so that you can step through it easily and watch. I typically use e for my event variable and e.target gets the target of the event. It will look something like this:
$('#hey').click(function(e){
debugger;
alert($(e.target).attr('data-uid'));
});
--- edit---
Adding my note below here so it is easier to read.
One thing I like to do in my onclick functions is to pass the this pointer. This is especially useful if you have multiple of the same kind of node that are calling the same function.
<a onclick="myName(this)" id="hey2">Read the blog</a>
<a onclick="myName(this)" id="hey3">Read the blog</a>
then, in the javascript you function looks like:
function myName(ptr)
{
$(ptr).....
// do some stuff
}
try using this:
function myName(uid){
alert(uid);
}
You dont need to wrap it in a jquery event handler, because you are already calling it as an onclick event from your Freemarker template.
Alternatively, you could do something like this:
<a data-uid="${item.uid}" id="hey">...</a>
And have your javascript like this:
$('#hey').click(function(){
alert($(this).data('uid'));
}

Dynamic button click doesn't work in Jquery

I want to develop dynamic presentation content in HTML5 presentation from
http://www.script-tutorials.com/creating-an-attractive-presentation-with-html5/
This tutorial is ok for static content . But I want to write dynamic content with jquery as the following:
$(document).ready(function(){
$.getJSON(url, function (data) {
for(var i in data)
{
output=" <button title='Next' id='nav-next' class='nav-next'>Click</button>";
}
$("#placeholder").append(output);
});
});
When click on button , I want to go next slide. But this event does not work. I want to call next function on javascript file. Please help.
You said "When click on button" and that is the answer use jQuery.on() method.
$('#nav-next').on('click',(function () {
// click code.
});
and then when you created DOM with id defined in .on will have click event dynamically attached.
You're not attaching an event to the new button, this can be done using the jQuery click method.
Also some other problems:
the loop seems to be redundant, you're not actually using anything in data.
output is being defined as a global variable in your example, use var to keep it in function scope.
Code:
$(document).ready(function() {
$.getJSON(url, function (data) {
// use var, your output was a global variable
var output = " <button title='Next' id='nav-next' class='nav-next'>Click</button>";
$("#placeholder").append(output);
// attach the click event to the new button
$('#nav-next').click(function () {
// TODO: Implement click method
});
});
});
Since you're not using data you can remove the call to getJSON safely currently. I assume you put it in for some reason though.

Passing argument to JS function from link onclick

I have a link that looks like this:
<a id="mylink" onclick="deleteHike( 3 );" href="javascript:void(0);">Yes</a>
It is able to call this JavaScript:
window.onload = function()
{
//Get a reference to the link on the page
// with an id of "mylink"
var a = document.getElementById("mylink");
//Set code to run when the link is clicked
// by assigning a function to "onclick"
a.onclick = function( hike_id )
{
// Somecode her
// But when I try to use the hike_id it displays as [object MouseEvent]
}
}
But the value that comes in is [object MouseEvent], not the number that I was expecting. Any idea why this happens and how to fix this? :)
Thanks!
You are trying to assign the function to your link in two different and conflicting ways.
Using the eval-ed function string, onclick = "function(value)", works but is deprecated.
The other way of binding the click handler in the onload event works too, but if you want a particular value to be passed, you'll have to change your script a bit because the value as given in the initial onclick is completely lost when you set the onclick to a new function.
To make your current method work, you don't need an onload handler at all. You just need this:
function deleteHike(hike_id) {
// Some code here
}
To do it the second way, which I recommend, it would look like this:
<a id="mylink" href="javascript:void(0);">Yes</a>
with this script:
function deleteHike(e, hike_id) {
// Some code here
// e refers to the event object which you can do nifty things with like
// - learn the actual clicked element if it was a parent or child of the `this` element
// - stop the event from bubbling up to parent items
// - stop the event from being captured by child items
// (I may have these last two switched)
}
function getCall(fn, param) {
return function(e) {
e = e || window.event;
e.preventDefault(); // this might let you use real URLs instead of void(0)
fn(e, param);
};
}
window.onload = function() {
var a = document.getElementById("mylink");
a.onclick = getCall(deleteHike, 3);
};
The parameter of a DOM event function is the event object (in Firefox and other standards-compliant browsers). It is nothing in IE (thus the need to also grab window.event). I added a little helper function for you that creates a closure around your parameter value. You could do that each time yourself but it would be a pain. The important part is that getCall is a function that returns a function, and it is this returned function that gets called when you click on the element.
Finally, I recommend strongly that instead of all this, you use a library such as jQuery because it solves all sorts of problems for you and you don't have to know crazy JavaScript that takes much expertise to get just right, problems such as:
Having multiple handlers for a single event
Running JavaScript as soon as possible before the onload event fires with the simulated event ready. For example, maybe an image is still downloading but you want to put the focus on a control before the user tries to use the page, you can't do that with onload and it is a really hard problem to solve cross-browser.
Dealing with how the event object is being passed
Figuring out all the different ways that browsers handle things like event propagation and getting the clicked item and so on.
Note: in your click handler you can just use the this event which will have the clicked element in it. This could be really powerful for you, because instead of having to encode which item it was in the JavaScript for each element's onclick event, you can simply bind the same handler to all your items and get its value from the element. This is better because it lets you encode the information about the element only in the element, rather than in the element and the JavaScript.
You should just be able to declare the function like this (no need to assign on window.onload):
function deleteHike(hike_id)
{
// Somecode her
// But when I try to use the hike_id it displays as [object MouseEvent]
}
The first parameter in javascript event is the event itself. If you need a reference back to the "a" tag you could use the this variable because the scope is now the "a" tag.
Here's my new favorite way to solve this problem. I like this approach for its clarity and brevity.
Use this HTML:
<a onclick="deleteHike(event);" hike_id=1>Yes 1</a><br/>
<a onclick="deleteHike(event);" hike_id=2>Yes 2</a><br/>
<a onclick="deleteHike(event);" hike_id=3>Yes 3</a><br/>
With this JavaScript:
function deleteHike(event) {
var element = event.target;
var hike_id = element.getAttribute("hike_id");
// do what you will with hike_id
if (confirm("Delete hike " + hike_id + "?")) {
// do the delete
console.log("item " + hike_id + " deleted");
} else {
// don't do the delete
console.log("user canceled");
}
return;
}
This code works because event is defined in the JavaScript environment when the onclick handler is called.
For a more complete discussion (including why you might want to use "data-hike_id" instead of "hike_id" as the element attribute), see: How to store arbitrary data for some HTML tags.
These are alternate forms of the HTML which have the same effect:
<a onclick="deleteHike(event);" hike_id=4 href="javascript:void(0);">Yes 4</a><br/>
<button onclick="deleteHike(event);" hike_id=5>Yes 5</button><br/>
<span onclick="deleteHike(event);" hike_id=6>Yes 6</span><br/>
When you assign a function to an event on a DOM element like this, the browser will automatically pass the event object (in this case MouseEvent as it's an onclick event) as the first argument.
Try it like this,
a.onclick = function(e, hike_id) { }

Issue with selectors & .html() in jquery?

The function associated with the selector stops working when I replace it's contents using .html(). Since I cannot post my original code I've created an example to show what I mean...
Jquery
$(document).ready(function () {
$("#pg_display span").click(function () {
var pageno = $(this).attr("id");
alert(pageno);
var data = "<span id='page1'>1</span><span id='page2'> 2</span><span id='page3'> 3</span>";
$("#pg_display").html(data);
});
});
HTML
<div id="pg_display">
<span id="page1">1</span>
<span id="page2">2</span>
<span id="page3">3</span>
</div>
Is there any way to fix this??...Thanks
Not sure I understand you completely, but if you're asking why .click() functions aren't working on spans that are added later, you'll need to use .live(),
$("#someSelector span").live("click", function(){
# do stuff to spans currently existing
# and those that will exist in the future
});
This will add functionality to any element currently on the page, and any element that is later created. It keeps you have having to re-attach handlers when new elements are created.
You have to re-bind the event after you replace the HTML, because the original DOM element will have disappeared. To allow this, you have to create a named function instead of an anonymous function:
function pgClick() {
var pageno = $(this).attr("id");
alert(pageno);
var data="<span id='page1'>1</span><span id='page2'> 2</span><span id='page3'> 3</span>";
$("#pg_display").html(data);
$("#pg_display span").click(pgClick);
}
$(document).ready(function(){
$("#pg_display span").click(pgClick);
});
That's to be expected, since the DOM elements that had your click handler attached have been replaced with new ones.
The easiest remedy is to use 1.3's new "live" events.
In your situation, you can use 'Event delegation' concept and get it to work.
Event delegation uses the fact that an event generated on a element will keep bubbling up to its parent unless there are no more parents. So instead of binding click event to span, you will find the click event on your #pg_display div.
$(document).ready(
function()
{
$("#pg_display").click(
function(ev)
{
//As we are binding click event to the DIV, we need to find out the
//'target' which was clicked.
var target = $(ev.target);
//If it's not span, don't do anything.
if(!target.is('span'))
return;
alert('page #' + ev.target.id);
var data="<span id='page1'>1</span><span id='page2'>2</span><span id='page3'>3</span>";
$("#pg_display").html(data);
}
);
}
);
Working demo: http://jsbin.com/imuye
Code: http://jsbin.com/imuye/edit
The above code has additional advantage that instead of binding 3 event handlers, it only binds one.
Use the $("#pg_display span").live('click', function....) method instead of .click. Live (available in JQuery 1.3.2) will bind to existing and FUTURE matches whereas the click (as well as .bind) function is only being bound to existing objects and not any new ones. You'll also need (maybe?) to separate the data from the function or you will always add new span tags on each click.
http://docs.jquery.com/Events/live#typefn

Categories

Resources