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_divelement. You have it defined asonclick="flyout('fb');", but the flyout function doesn’t return anything. I changed the code below so thatflyoutreturns a function and encapsulates the value ofdatain its closure, in case you want to use this same function with different values for thedataparameter.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
delegatemethod to bind a function to any event.HTML:
JS:
EDIT:
According to the latest jquery documentation use of the
livemethod is deprecated, usedelegateinstead.