jQuery .load function makes script only excecute once - javascript

I'm trying to use jQuery's .load function to load a div element from one page to another. But it makes the whole script only run once.
I've seen a few similar question here on SO, but none of these seem to fit my problem. I've tried things such as changing .click to .one as well as adding new Date().getTime() and $.ajaxSetup({cache: false}) to prevent cashing. None these works.
I'm not sure what the problem is, but it seem to occur only when I use the .load function. I've attached a simplified version of my script.js file below:
script.js
$(function() {
$("a").click(function(e) {
var url = $(this).attr("href");
$("body").load(url + " .container");
e.preventDefault();
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>Index page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h2>This is the index page</h2>
Index page
<br>
Second page
</div>
<script src="script.js"></script>
</body>
</html>
The second.html looks pretty much the same as the index.html file.

Your event handlers are only bound to the anchors on the first page, I would use event delegation so that I would not have to bind the handlers every time a new page is loaded.
$(document).on('click', 'a', function(e){
var url = $(this).attr("href");
$("body").load(url + " .container");
e.preventDefault();
});

I had the same problem. I resolved it with calling the Javascript after the load() again. Here is the snippet
$.getScript('<your script>');

Related

Call function in JavaScript and not fire(header script is jQuery and jQuery Mobile)

I have a page like this (index.php):
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<?php //add .min.js file when all programming done ?>
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/_jquery.mobile-1.4.0.css">
<script src="js/_jquery-2.1.0.js" type="text/javascript"></script>
<script src="js/_jquery.mobile-1.4.0.js" type="text/javascript"></script>
<script src="js/main.js" type="text/javascript"></script>
<script src="js/sign.js" type="text/javascript"></script>
</head>
<body>
<div data-role="page">
<div data-role="header" id="nav"><?php include_once 'nav.ui.php'; ?></div>
<div data-role="main" class="ui-content" id="ui">
<input type="button" id="optionUpdate">
</div>
<div data-role="footer" id="footer"><?php include_once 'footer.ui.php'; ?></div>
</div>
</body>
</html>
And in main.js I have:
$('#optionUpdate').click(function () {
optionUpdate();
});
function optionUpdate() {
alert('hi');
}
The problem is: when I click on the button, the event is not run. But if
add the onclick event to the button with optionUpdate();, it works!
Why?
How can I fix this?
In jQuery Mobile, you need to wrap functions in page events not in .ready(). The latter fires once per document, where page events fires per page / view.
If you are using jQuery Mobile with Ajax enabled and have multiple pages or load external pages, if you use .ready(), functions inside it will execute once only.
Important: Use $(document).bind('pageinit'), not $(document).ready():
The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate, and the DOM ready handler only executes for the first page. To execute code whenever a new page is loaded and created, you can bind to the pageinit event. This event is explained in detail at the bottom of this page.
The equivalent to .ready() in jQuery Mobile is pagecreate (pageinit is deprecated as of 1.4). Wrapping functions in pagecreate ensures that those functions fire whenever pagecreate event occurs.
$(document).on("pagecreate", function () {
$('#optionUpdate').on("click", function () {
optionUpdate();
});
function optionUpdate() {
alert('hi');
}
});
You can bind specific functions to a specific page by delegating event to that page.
$(document).on("pagecreate", ".selector or #page_ID", function () {
/* functions for this page only */
});
Demo
Note: this answer is more about jQuery than jQuery Mobile. With the mobile library, code that needs to run when the page is updated by the framework should use page events as described in other answers.
Because your "main.js" file is imported in the <head> of your page, when the code runs it won't find the "optionUpdate" element in the page: the browser will not have parsed that yet.
Three options:
Use event delegation:
$(document).on('click', '#optionUpdate', optionUpdate);
Use a "ready" handler:
$(function() {
$('#optionUpdate').click(function () {
optionUpdate();
});
});
Move your <script> tag to the end of the <body>.
You're trying to reference elements before they exist. Wrap your code in a DOM ready handler:
$(document).ready(function() {
$('#optionUpdate').click(function () {
optionUpdate();
});
});

Attaching onclick event to element is not working

I just started learning Javascript, and I know next to nothing. I am trying to attached an onclick event to an element in my HTML.
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
This is my code so far. Nothing happens when the element with the ID of header is clicked on. What am I doing wrong?
the following is my HTML code
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
<script src="testing.js"></script>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
</body>
</html>
The issue is, that you try to load a html element, which does not "exists" when the javascript function is executed, because the dom has not finished loading.
To make your code work, you can try following solutions:
Place your script tag below in the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
<script src="testing.js"></script>
</body>
</html>
Add an event handler to check if the window element is ready:
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded(){
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
}
Another solution would be to use jquery framework and the related document ready function
http://api.jquery.com/ready/
I think the solve you are looking for is
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").setAttribute("onclick", joinList);
Your code seems straight forward, maybe your script is running before the DOM fully loads. To keep it simple across all browsers we can place a self executing anonymous function at the end to initiate all your scripts after DOM loads.
<html>
<title></title>
<head></head>
<body>
html here!!
<script>
(function() {
//Any other scripts here
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
})();
</script>
</body>
</html>
The above is purely javascript, not to be confused with the shorthand (see below) of the jquery "document onready" function (you would need to add jquery to your pages).
$(function() {
//your javascript code here
});
Why using self executing function?

javascript tag trigger - code position on page

i use that tag to alert me when a tag has been shows up
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
<iframe></iframe>
</body>
</html>
strange , since this code working :
<html>
<head>
</head>
<body>
<iframe></iframe>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
</body>
</html>
why the Js need to under the tag to work?
what's the problem here?
Because the code in a script tag is executed immediately. And in the first example the iframe doesn't exist at that time. But what you can do is to wrap you code into an onload (for the main page) event. E.g.:
window.onload = function() {
//your code
}
Then it doesn't matter where the code is placed.
Iframe tag does not exist at the moment you are trying to access it.
You may check that by simply alerting array length, like
alert(document.getElementsByTagName('iframe'));
Have you thought about executing your javascript after the page is loaded? You may use some frameworks like jQuery to facilitate crossbrowser issues. Or just put all your javascript code to the very bottom of body.

jquery toggle in a pop up modal form

I want to toggle between a div on a pop-up modal form. The problem i see is the document.ready() function on the modal page, which tries to load the parent form. It distorts the whole page and tries to show automatically if i load the main parent form. Is there something like div.ready()? how do i include this code on my pop up modal form?
Toggle code here
<html>
<head>
<title>jQuery test page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#clickMe").click(function() {
$("#textBox").toggle();
});
});
</script>
</head>
<body>
<a id="clickMe">Toggle my text</a>
<br />
<div id="textBox">This text will be toggled</div>
</body>
Yes, such expressions like DOM_ELEMENT.ready() exists and very useful in scenarios like the one you are facing right now.
Update:
I found that this plugin is doing what you need :
jQuery.elementReady()
Examples:
1:
Change the source of a specific image as soon as it is loaded into the
DOM (before the whole DOM is loaded).
$.elementReady('powerpic', function(){
this.src = 'powered-by-jquery.png';
});
2:
If you want to have the jQuery object instead of the regular DOM
element, use the $(this) function.
$.elementReady('header', function(){
$(this).addClass('fancy');
});
3:
Chain multiple calls to $.elementReady().
$.elementReady('first', function(){ $(this).fancify(); })
.elementReady('second', function(){ $(this).fancify(); });
4:
Use the ‘$’ alias within your callback, even in noConflict mode.
jQuery.noConflict();
jQuery.elementReady('header', function($){
$(this).addClass('fancy');
});
5:
Change the polling interval to 100ms. This only works if $.elementReady() has not yet been called.
$.elementReady.interval_ms = 100;

Basic jQuery .load Problem

I am trying to use jQuery's .load function to dynamically load content into my webpage. This seem so simple, but I cannot make it work. To try and figure it out, I made a test page with just basic structure, but the external content still won't load:
jquery.html
<html>
<head>
<title>JQuery Test</title>
<script src="jquery1.5.min.js"></script>
</head>
<body>
<script>
$('#foo').load('test.html');
</script>
<div id="foo"></div>
</body>
</html>
test.html
<p>Text text</p>
I'm sure I have made a tiny error, but I can't find it anywhere!
You need to encapsulate your script in the $(document).ready() otherwise #foo won't exist when the script is executed:
<script>
$(document).ready(function(){
$('#foo').load('test.html');
});
</script>
You need to wait for the document to be ready before you can access the DOM. Just add a $(document).ready() around your original code:
<html>
<head>
<title>JQuery Test</title>
<script src="jquery1.5.min.js"></script>
</head>
<body>
<script>
$(document).ready( function() {
$('#foo').load('test.html');
});
</script>
<div id="foo"></div>
</body>
</html>
or if you want a shorter code:
$(function() {
$('#foo').load('test.html');
});
Informally, what's happening is that, as your browser reads the code you wrote, it's drawing its contents as it goes along. When it reaches your <script> tag, it executes it. But when $("#foo") gets executed, the browser's still processing the <script> and hasn't reached the part of the code where you told it there's a div called foo, so the browser doesn't know it exists, and jquery will just find nothing.
Of course, the idea that the browser will just sequentially read your code and render it as it goes is naive at best, so while it might seem that just moving the <script> tag to the bottom of the code would work, you're not actually guaranteed it will work. Instead, the browser will notify you when it's done drawing the page by firing a load (and possibly a DOMContentLoaded) event. So all code that depends on the whole html being drawn should be executed in an event handler bound to those events.
jQuery makes waiting for the page to be loaded easy, just use something like this:
$.ready(function() {
doStuff();
});

Categories