Question

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>");
}
Was it helpful?

Solution

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.

OTHER TIPS

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top