JQuery : Removing DOM objects that have been added in load() - javascript

File contents are given below. I have a button, "load_button", whose click event triggers a load() function. The html file loaded with the function contains another button, "my_button". The callback of the load() function adds a handler for the click event of "my_button". The problem is, every time I press "load_button", a new click event handler is added, and the alert in the event handler pops up multiple times. I want to delete previously created "my_button" with its event handler, before creating the new one. What I tried is adding the following command, where its commented out in the file descriptions below.
$('#page').empty();
No luck. I wanted a general solution, since I'll have other DOM objects to be removed. How can I remove them?
Also, it does not work when I replace
$('#page').on('click', '#my_button', function () {
with
$("#my_button").click(function() {
Why isn't it working? Isn't the callback function of load() supposed to be run after the loading is done, and DOM objects are available?
main.html
<html>
<head>
...
<script src="main.js"></script>
</head>
<body>
...
<a id="load_button">Load!</a>
<div id="page">
</div>
</body>
</html>
1.html
<div>
<a id="my_button">Go!</a>
</div>
main.js
$(document).ready(function(){
$('#load_button').click(function() {
// $('#page').empty();
$("#page").load('1.html', load_scripts());
});
});
function load_scripts() {
$.getScript('script.js');
}
script.js
$(document).ready(function(){
$('#page').on('click', '#my_button', function () {
// $("#my_button").click(function() {
alert('COWABUNGA!');
});
});

It looks like you don't need to load scripts dynamically at all. Try a main.js that looks like this:
$(document).ready(function(){
$('#load_button').click(function() {
$("#page").load('1.html');
});
$('#page').on('click', '#my_button', function () {
alert('COWABUNGA!');
});
});

Related

Changing <script> tag dynamically with jQuery

I've been trying to figure out if it's possible to dynamically change the src of a <script> tag (or load a new script tag) and have the previous script no longer execute. Example below:
index.html
<button id="action">Click</button>
<script id="javascript-file-script" type="text/javascript" src="/js/oldjsfile.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#javascript-file-script").remove();
setTimeout(function() {
$('body').append('<script id="javascript-file-script" src="/js/newjsfile.js" type="text/javascript"><\/script>')
}, 100);
});
</script>
oldjsfile.js
$(document).ready(function() {
console.log('old file loaded');
$('#action').click(function() {
alert('old');
});
});
newjsfile.js
$(document).ready(function() {
console.log('new file loaded');
$('#action').click(function() {
alert('new');
});
});
Before changing the javascript file, clicking on #action would have 1 alert "old". Once I change the script, and click on #action I get both alerts "old" and "new". Is there a way to "unload" the previous file so that the original click function is removed/not executed?
I'm looking for a solution other than changing ids or editing the scripts. I'm thinking this isn't possible because the script is already in memory.
That isn't possible. It is already loaded and running. You should consider using .on and .off for binding to the click event.
To begin, you definitely do not want to load and unload scripts as that will cause other problems and loading scripts should be done asynchronously.
For your first event, you did everything fine.
For the second event, it has to happen when something else happens. In my snippet below, I created another button and when that was clicked it took off the old event and added the new one. This doesn't have to happen on button click it can be on anything but you have to remove the old event with unbind and create a new one just like you did originally.
To try the example below, click the first button and you'll see an alert of 'old'. Then click on the second button and click on the first button again and you'll see 'new'.
$(document).ready(function () {
// The original click event.
$('#action').click(function () {
alert('old');
});
// Let's set up a reference to our new button which will cause the #action click to change.
$('#changeAction').click(function () {
// Unbind the previous click event associated with #action:
$('#action').unbind('click');
// Create the new click event.
$('#action').click(function () {
alert('new');
});
});
});
<button id="action">Click</button>
<button id="changeAction">Click me to change the action of the first button</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Jquery Custom event from page loaded with AJAX called only once

I stack with a problem. There is a page with script to load child page and log custom event which is triggered in Subform.
----Default.aspx----
<body>
<input type="button" class="clickable" value="Load child doc" />
<hr />
<div id="container"></div>
</body>
<script>
var clickHandler = function () {
$.ajax("Subform.aspx", {
method: "GET",
success: function (data) {
$('#container').html(data);
}
});
}
$(function () {
$('body').on('click', clickHandler);
$('body').on("dataLoaded", function (param) {
console.info("Custom event triggered", param);
})
});
----Subform.aspx has script which triggers custom event "dataLoaded" ----
<html>
<header>
<script src="scripts/jquery-1.7.1.js"></script>
</header>
<body>
..context of Subform...
<script>
$(function () {
$('body').trigger("dataLoaded", { key: "value from sub form" });
console.log("ChildPage loaded. dataLoaded event triggered")
})
</script>
.....
</body>
</html>
Issue is that after subform loaded into container (and document ready triggered in ajax-loaded file - I see message: "childPage loaded.."), custom event "dataLoaded" triggered, but handler called only once - first time ajax loaded childPage. All other ajax calls load context of the subform, text "ChildPage loaded. dataLoaded event triggered" is logged, event "dataLoaded" triggered but event handler for custom event is not called anymore..
Whats going on here? I expect that every time child page loaded and custom event triggered, handler for it will be invoked.
Problem/solution found.
Subform.aspx was an HTML page with JQuery script reference tag in header. When subform gets loaded into parent #container div - subform reloaded jQuery and handler got lost.
Solution was easy - in subform.aspx remove <script> tag and all other tags which can make main document invalid, like body, html, header. Leave only content, somewhat like this
<div>
SubForm
Ajax response....
<script>
$(function() {
debugger;
$('#container').trigger("dataLoaded", { key: "value from sub form" });
console.log("ChildPage loaded. dataLoaded event triggered");
});
</script>
After this change custom event triggered in dynamically loaded page got handled.

Toggle text with function called with onclick

my question is a short one but I couldn't figure it out by myself. I've got a function like -> http://jsfiddle.net/gtU56/ . I'm calling a javascript-function with an event-listener(onclick) in my html-code. The function itself is more complex but I need the last snippet. By clicking 'Show More' the text should change. Why won't the text change?
Because the toggleText function isn't available when the html code is rendered.
In other words the function isn't set until the page is ready so the onclick function doesn't reference anything.
Either have the function like here http://jsfiddle.net/gtU56/2/
or have it in the head of the page because its needs to be ready immediately
If you want it to wait for the ready state you can do the following and remove the onclick action all together
http://jsfiddle.net/gtU56/7/
$(".text").click(function()
{
$(".text").toggle();
});
toggleText = function () {
$('.text').toggle();
}
check here http://jsfiddle.net/gtU56/3/
It's because of how you're loading the function. Switch it from onLoad to no wrap (head) and it works fine.
jsFiddle example
Using jsFiddle's onLoad wraps your function in a window.onload call like this:
<script type="text/javascript">
//<![CDATA[
$(window).load(function(){
function toggleText() {
$('.text').toggle();
}
});//]]>
</script>
While no wrap (head) just adds it normally like this:
<script type="text/javascript">
//<![CDATA[
function toggleText() {
$('.text').toggle();
}
//]]>
</script>
since you are already claiming having jquery, you need not use inline javascript. try this
var elems = $('.text');
elems.click(function(){
elems.toggle();
});
fiddle : http://jsfiddle.net/gtU56/5/
$('.text').click(function() {
$('.text').toggle('slow', function() {
// do your animation..
});
});
​
Js Fiddle
This is the solution - http://jsfiddle.net/gtU56/6/
You need to first make sure that the function is registered after page load. Then, bind a click event to the div.
Hope this helps!
First you should organize you jQuery code like this:
$.(document).ready(function() {
// enter jQuery code here
});
Otherwise you're accessing a not completly loaded html document.
Also, you don't need the event-listener if you are using jQuery.
This should work for you:
$.(document).ready(function() {
$('.text').click(function() {
$(this).toggle();
});
});
Is very easy. You can use ID or CLASS.
onclick="$('NAME ID or CLASS').toggle(ANIMATION or DURATION);"
<div>
<div class="text" onclick="$('.text2').toggle(400);">Show More</div>
<div class="text2" style="display:none">Show Less</div>
</div>

JQuery: How can I extend a script over some dynamically loaded content?

I have a little problem that I was hoping some of you could help me out with.
On clicking a button, I would like to update a div with the content of another page.
Let's say that homepage.html is like this:
<html>
<head>
<script type="text/javascript" src="JQUERY.JS"></script>
<script type="text/javascript">
$(function()
{
$(".alert").click(function()
{
alert("HELLO");
return false;
});
$(".load").click(function()
{
$("#content").load("FILE.HTML");
return false;
});
});
</script>
</head>
<body>
CLICK ME
<div id="content"></div>
</body>
</html>
A rather simple file.
Now let's say that FILE.HTML has this line only:
CLICK ME
Now what I am looking for is: when i click .alert, the alert box pops up. I don't know why it doesn't.
So my question is: why is my loaded code not affected by the script?
Thank you for your help.
You need to use the jQuery Delegate to achieve that...
The contents from file.html are not present the moment you attach the click event to the ".alert" items (actually there are no .alert items when that code runs!).
You need to use jQuery's delegate or live methods which use event bubbling in order to capture events not only from existing elements but also from new elements that are inserted in the DOM later.
This also has the nice side effect of using only one event handler instead of one for each .alert element.
You have to use $.live:
$(".alert").live('click', function()
{
alert("HELLO");
return false;
});
You don't have to wait until you add in your dynamic content, this function applies your event handler to all future elements that match your selector.

Button onclick to click() jquery

I have a button that reacts to onclick() at the moment, but I want it to work with jquery.
$('#nupp1').click(function() {
raiseButtonAction(realPlayer, gameState);
});
raisebuttonaction is in another .js
This piece of code isn't working.
Am I doing something wrong?
edit1:
$(document).ready(function() {
$('#nupp1').click(function() {
raiseButtonAction(realPlayer, gameState);
});
});
Assuming you have this:
<head>
<scripts />
</head>
<body>
<a id="nupp1"></a>
</body>
You code will not work. jQuery will not be able to find the element. The element must exists for that function to work. So
<a id="nupp1"></a>
<script />
Will work because a is being rendered before the script.
You can also use $(document).ready or $() to execute your function when the DOM nodes load.
Or you can use jQuery.live.
jQuery API
ready Specify a function to execute when the DOM is fully loaded.
live Attach a handler to the event for all elements which match the current selector, now and in the future.

Categories