Dom loads two times - javascript

I have a very weird problem. I am using jQuery and i am using the $(function () to load functions when the dom is loaded. But with a unknown reason the code in the $(function () will run a second time. A preview is at: http://development.devhouse.nl/news/3/het-nieuwste-nieuwsbericht you will get 2 alert prompts, but there is only 1 written in a $(function () . The exact code is:
<script type="text/javascript">
$(function () {
alert('Test');
});
</script>
And the whole source can be found here(open the source in your browser): http://development.devhouse.nl/news/3/het-nieuwste-nieuwsbericht
Please help me. I am hopeless....
Tom

I suppose because the script is in your html body instead of in the head. Move it to the head, and it only fires once.
Is there a reason you have it there?
EDIT: For clarification, as Marcel Korpel noted, scripts can be nested in the body, and there can be performance reasons to have them at the end. But in this situation, the script was nested inside an element within the body. This works, but can lead to unexpected behavior if that element is manipulated in certain ways.

$().ready(function(){
alert('Test');
});

Related

$(window).load(function() fails to execute after completely loaded document

I have failed to find the answer in the following:
I have an html document that loads a couple of other htmls.
This is done perfectly.
However, in on one of the included htmls, the "navmenu.html", I would like, after everything is comlepetly loaded, to execute a script found in load() to modify "menu1" element's class, which is in the included "navmenu.html".
After the ready() function, the load() function is executed before the "navmenu.html" is really & completely included in the document, since I get the error message that the element "menu1" is not found.
If I pause the action by an alert() at the beginning of load() - then the menu1 element is found - since this delay caused by the alert() gives time to the ready() function to complete.
So, is there a way to solve this?
Thank you in advance.
<body>
<div id="navmenu"></div>
<div id="carousel"></div>
</body>
<script language="javascript" type="text/javascript">
jQuery( document ).ready(function( $ ) {
$('#navmenu').load('navmenu.html');
$('#carousel').load('carousel.html');
});
$(window).load(function() {
var element = document.getElementById("menu1");
element.classList.add("active");
});
</script>
jQuery.load() has the following signature (url,data,callbackFunction).
You could try the followind :
jQuery( document ).ready(function( $ ) {
$('#navmenu').load('navmenu.html',[],function(){
$('#carousel').load('carousel.html',[],function(){
var element = document.getElementById("menu1");
element.classList.add("active");
});
});
});
Thank you so much Radu Toader for the reply.
It worked !!!
(I am not sure if this is the right way to answer, since it's my first question to the group.)
I also tried the following, since the element was in "navmenu.html" and had a separate line for the carousel.
$('#navmenu').load('navmenu.html',[],function(){
var element = document.getElementById("menu1");
element.classList.add("active");
});
$('#carousel').load('carousel.html');
I also tried your answer where load.carousel was called by the load.navmenu and it also worked.
Do you suggest that I should use your "more complex" solution instead of the separated line for the carousel?
Thanks again.
Dimitrios

Can someone explain to me how this is possible? (Picture in comments)

So I'm trying to link up my html and javascript files in notepad++, but it isn't working properly.
I wanted to know how it is possible that it writes test, but doesn't remove the div. Can anyone explain this? Thanks in advance!
1, jQuery isn't linked. Meaning, you don't have <script type='text/javascript' src='myjQueryfile.js'></script> in your HTML, you'll want to put it before your script.
2:
Because the element with the ID of blue, doesn't exist yet. The DOM - basically the object of your HTML - has yet to be constructed when your script is run, which in this case is the top of the page, before blue comes into existence. You'll want to use an event to fix this, typically $(function(){ ... }); which will execute your code when the DOM is ready.
Also, document.write just writes code then and there, meaning exactly where the document.write calls is made, the HTML will be outputted.
You should have linked jquery. You're trying to use it without having it linked.
The script is loaded in the head. At the time the script executes the body of the document is not built, so nothing is removed. If you were to use the document.ready callback (and had properly included jQuery) it would work
$(function(){ $("#blue").remove(); });
A plain js version of this is
window.onload = function(){
var b = document.getElementById("blue");
b.parentNode.remove(b);
};
At the time the script runs, only the portion of the document up to the <script> tag has been loaded. You need to delay until the DOM has fully loaded before the script can target the DOM:
document.addEventListener("DOMContentLoaded", function(event) {
$("#blue").remove();
});

Hide Image when another image is clicked

this seems to be simple.. but I am a bit noobish with jquery, maybe I am doing something silly wrong?
I want to click an image, and on that click, hide another image right next to it.
<script type="text/javascript">
$("#butShowMeSomeUnits").click(function() {
$('#arrowUnitspic').hide();
});
</script>
Id's are correct as per the two images. What am I missing? Debugging it, the code never gets fired...
Thanks
EDIT
I had my control as a nested control on an asp masterpage, and its id was being rewritten. I have now fixed the id, but I still cant get any joy... I also see my markup is being rendered as an "input", would that make a difference?
<head>
<script src="js/jquery.min.1.5.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#butShowMeSomeUnits").click(function () {
$('#arrowUnitspic').hide();
});
});
</script>
</head>
<body>
<input type="image" src="bookings_media/buttons/show-me-some-units.png" onmouseout="this.src='bookings_media/buttons/show-me-some-units.png'" onmouseover="this.src='bookings_media/buttons/show-me-some-units_orange.png'" id="butShowMeSomeUnits" name="ctl00$ctl00$ContentPlaceHolder1$bookings_right_content$butShowMeSomeUnits">
</body>
EDIT
JS Fiddle
If there is any confusion... the JS fiddle I spooled up with the exact code also does not work...
You need to do do on page ready:
<script type="text/javascript">
$(document).ready(function() {
$("#butShowMeSomeUnits").click(function() {
$('#arrowUnitspic').hide();
});
});
</script>
Edit:
The fiddle you provided did not work until I chose jQuery 1.10.1 from the dropdown. You will notice your onmouseover changes the element first, but once you click on the input it does hide the image. Can you verify this works the same for you?
If the answer is no then I don't think you are loading the jQuery library on your page. To check this should work:
if (typeof jQuery != 'undefined') {
alert("jQuery library is loaded!");
}else{
alert("jQuery library is not found!");
}
In addition it might be helpful to see what errors your browser console /dev tools is showing.
Wrap the code in jQuery.ready() event. And also check whether jquery js file is loaded or not.
$(document).ready(function(){
$("#butShowMeSomeUnits").click(function() {
$('#arrowUnitspic').hide();
});
});
You code looks good and works check here
What you might be missisng is either:
to load jQuery script in the head of your page.
to include $(document).ready(function() { //code here }); in case your <img> tags are after the script in the page code. This is so your code loads when page is ready/loaded.
Steps that may help you:
make sure you integrate jQuery lib right. (to check that you might wanna open console on chrome and type $("html").hide(); and see if the current page dissapears)
make sure your custom JS file or code is UNDER the including of jQuery lib.
very good starting point with jQuery is to put everything in $(document).ready() as below example:
$(document).ready(function(){
$("img").click(function(){
$("img").hide();
$(this).show();
});
});

jQuery not loading at all

I'm trying out jQuery for the first time, and I'm not sure how to make it work properly. I've included the following code near my opening <head> tag:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
Followed by the following jQuery code:
<script>
$('.darkmask > img').hover(function(){
$(this).parent().toggleClass('darkmask-hover');
})​
</script>
Unfortunately, this code doesn't work when I try it in a browser, or in JSFiddle. However, when I set JSFiddle's framework to load jQuery itself, rather than loading jQuery through my own code, the animation works properly.
Am I loading jQuery wrong? If so, what's the right way?
PRoblem is, your code in JSFiddle is executed on the loading on the page. In your code instead, the execution happens when the HTML elements are not yet loaded because it's in the HEAD, so the selectors like .darkmask actually refer to... nothing.
The solution is to use:
$(document).ready(
function()
{
... your code here
}
To ensure that it is executed when the page is loaded and ready, all the HTML elements are there and therefore JQuery selectors can operate on something.
Are there any HTML elements when the code is executed?
Try:
$(function () { // this function executes when the page loads
alert(x);
// put your code here
});
Wrap your entire code in the following:
$(document).ready(function() {
//ALL CODE GOES HERE
});
Wrap your code in:
$(function() {
.... Your code here ...
});
It will mean your code is executed after the DOM tree is loaded.
You do need to wrap your jQuery code within the ready function, like this:
$(document).ready(function(){
// put your code here.
});
Also make sure your script tags have type="text/javascript" as an attribute otherwise it won't get run as javascript.

weird jQuery JSON function... whats going on here?

Im browsing the flot examples here http://people.iola.dk/olau/flot/examples/turning-series.html
(view source once there)
I came across this :
<script id="source" language="javascript" type="text/javascript">
$(function () {
var datasets = {
"usa": {...
The $(function() part. I get that its an anonymous function, I dont get why it is used here. Wouldnt this be just as good :
<script id="source" language="javascript" type="text/javascript">
var datasets = {
"usa": {...
I checked over at the jQuery docs (http://api.jquery.com/) and found no special use for function()
$(function () {
Is for executing the code when the DOM is ready, it's a document.ready handler in jQuery, the same effect as:
$(document).ready(function () {
You want to run certain things on document.ready so that the elements are there, for example if you're using $(".class") as a selector, you wouldn't want that code to run until the DOM was fully loaded, so the elements you're looking for are there, ready to be found by the selector...this means your code would always work, even if it's in the <head>.
For documentation, look at jQuery(callback) in the API.
This is shorthand for $(document).ready(handler) which waits until the DOM is fully loaded before running the anonymous function.
In jQuery, $(function() { is shorthand for $(document).ready(function() {.
Yes, your 2nd part would work equally well, but the first one guarantees that the entire DOM for the page is loaded before it is executed.

Categories