Jquery Custom event from page loaded with AJAX called only once - javascript

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.

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>

click function doesnot work after auto page refresh

I am refreshing my page every 25 seconds using Javascript.But another Javascript for click function works fine before page refresh whereas after page refresh it doesnot work.
HTML:
<div id="refreshOnline">
<div id="refreshData">
//Set of Functions
<a target="_blank" href="http://example.com/startgame.php?gname='.$key['gameName'].'&player='.$_SESSION["uname"].'&type=t20" class="btn btn-primary btn-sm popup-game" id="popup-game" >Play Now!</a>
</div>
</div>
Javascript:
<script type="text/javascript">
//Script to refresh Div
function show_data()
{
$('#refreshOnline').load('main.php #refreshData');
}
setInterval('show_data()', 25000);
//Script to oprn link in new window
$('#popup-game').click(function (event) {
event.preventDefault();
alert("Working");
window.open($(this).attr("href"), "popupWindow","width=600,height=600,scrollbars=yes");
});
</script>
Before refresh, link opens in new window whereas after execution of refresh script, link opens in new tab instead of new window.
The code:
$('#popup-game').click(...
binds a click handler to the #popup-game element that exists at the moment that code runs. If that element is a child of #refreshOnline it will be replaced when you refresh #refreshOnline and so the new version of that element will not have a click bound. You can use a delegated event handler instead:
$('#refreshOnline').on('click', '#popup-game', function(event) {
event.preventDefault();
alert("Working");
window.open($(this).attr("href"), "popupWindow","width=600,height=600,scrollbars=yes");
});
This actually binds the handler to #refreshOnline, but when a click occurs jQuery automatically checks if it was on a child element that matches the selector in the second parameter and only calls your function if it does.
For more information see the .on() doco.
This is because the click handler is not assigned to the new content. Set them again after you have changed the content like so:
<script type="text/javascript">
//Script to refresh Div
function show_data()
{
$('#refreshOnline').load('main.php #refreshData');
setClickers();
}
function setClickers(){
//Script to oprn link in new window
$('#popup-game').click(function (event) {
event.preventDefault();
alert("Working");
window.open($(this).attr("href"), "popupWindow","width=600,height=600,scrollbars=yes");
});
}
$(function(){
setClickers();
setInterval('show_data()', 25000);
});
</script>
You should register the click event every time you refresh the content of the div.

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

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!');
});
});

How to handle an event by the handler defined in the javascript which creates the event?

I open a html page with a myApp.js included like this:
<html>
<body>
......
<div id="dynamicForm"></div>
......
<script type="text/javascript" src="myPath/myApp.js"></script>
......
</body>
</html>
and then I want to load a form defined in myApp.js dynamically on this html page at ("#dynamicForm"), the myApp.js has some lines like this:
.....
//load the form on the html page
$('#dynamicForm').html(createDynamicForm()).show();
.....
//the function creating the form
function createDynamicForm(){
var jqForm=$('<form id="dynamicFormId">'
......
+ '<button id="btn">OK</button>'
+ '</form>');
$('body').append(jqForm);
return jqForm;
}
.....
//click the button on the form to trigger the alert box
("#btn").click(function(){
alert("you click the button");
});
I can load the form on the html page, but when I click the "OK" button on this dynamically loaded form, the alert doesn't pop up, apparently this is because myApp.js is loaded with the html page before the dynamic form is created, the "click" event can not be handled by the handler defined in myApp.js that creates the form. how can I fix this problem?
As you're trying the #btn dynamically, so you need a delegate event handler and for that purpose you should use .on().
$('body').on('click', '#btn', function(){
alert("you click the button");
});
Syntax of .on() for delegate event looks:
$(staticElement).on( eventName, target, handlerFunction );
Here, staticElement points to an element that belongs to DOM at page load i.e. which is not dynamic.

How to trigger an iframe event Jquery

I have an IFRAME and I want to trigger an event (which is inside the iframe) from the parent of an IFRAME:
Just a rough example of what I am trying to do :
<iframe id="i">
<div id="test"></div>
<script>
$(document).ready(function() { // Event is binded inside the iframe
$("#test").live({ click : function() { alert("hello"); } });
});
</script>
</iframe>
<script>
$(document).ready(function() { // Want to trigger it from outside the iframe
$("#i").contents().find("#test").trigger("click");
});
</script>
Your jquery is correct only problem is that that you are doing this when document is ready but at that time iframe is not getting fully loaded therefore div doesn't exist at that time and not triggers click.
Change your main page script to
$(document).ready(function() {
//want to trigger it from outside the iframe
$("#i").load(function(){
$("#i").contents().find("div").trigger("click");
});
});
try this
ger javascript event from within an iFrame
but look at answer from Gilly
document.myFrameName.myFunction();
regards

Categories