how to use jquery in included html? - javascript

sorry for the title...
so i separated the index.html into divs then i called the contant using :
<script>$(function(){$("#work_bunch").load("wb.html"); });</script>
and it works fine but i wont to use jquery on the elements in wb.html
i used this in index :
<script type="text/javascript" src="java_scripts/wb_op.js"></script>
what ever i write in the .js file it seems to work fine in the index
but i can't select any element in wb.html
for example (if img5 is an element wb.html) :
$("#img5").mouseover(function(){
$(img5).fadeOut(2000);
});

You need to use event delegation:
$(document).on('mouseover', '#element_in_wb_page', function() {
// your function
});
In your case:
$(document).on('mouseover', '#img5', function() {
$(this).fadeOut(2000);
});

Delegate the event:
$("#work_bunch").on("mouseover", "#img5", function(){
$(this).fadeOut(2000);
});
When DOM was ready your elements were not there they come into view afterwards so at the time of DOM ready all the events were bound to existing elements. If any element is generated dynamically or put into the view via ajax any event will not be bound to them.
So the solution to cater this issue is to try to delegate the event to the closest static parent whenever possible, although you can delegate to document also but that is way expensive in lookup of that dom elements.
explaining syntax:
$(parentToDelegate).on(event, selector, callbackFn);

If you are including .js in head tag, then you need to make use document.ready()
$(document).ready(function() {
$("#img5").mouseover(function(){
$(this).fadeOut(2000);
});
});

here is what i found to be more general solution
use
$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
});
instead of
$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
});
because:
- The document ready event executes already when the HTML-Document is loaded.
- The window load event executes a bit later when the complete page is fully loaded, including all frames, objects and images.

use delegate method on if content added dynamically
$("#work_bunch").on("mouseover", "#img5", (function(){
$(this).fadeOut(2000);
});
and typo issue $(img5) to $("#img5")

Related

Types of JQuery On Load Functions [duplicate]

What are differences between
$(document).ready(function(){
//my code here
});
and
$(window).load(function(){
//my code here
});
And I want to make sure that:
$(document).ready(function(){
})
and
$(function(){
});
and
jQuery(document).ready(function(){
});
are the same.
Can you tell me what differences and similarities between them?
$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
console.log("document is ready");
});
$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
console.log("window is loaded");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Query 3.0 version
Breaking change: .load(), .unload(), and .error() removed
These methods are shortcuts for event operations, but had several API
limitations. The event .load() method conflicted with the ajax .load()
method. The .error() method could not be used with window.onerror
because of the way the DOM method is defined. If you need to attach
events by these names, use the .on() method, e.g. change
$("img").load(fn) to $(img).on("load", fn).1
$(window).load(function() {});
Should be changed to
$(window).on('load', function (e) {})
These are all equivalent:
$(function(){
});
jQuery(document).ready(function(){
});
$(document).ready(function(){
});
$(document).on('ready', function(){
})
document.ready is a jQuery event, it runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all the content.
window.onload fires later (or at the same time in the worst/failing cases) when images and such are loaded. So, if you're using image dimensions for example, you often want to use this instead.
Also read a related question:
Difference between $(window).load() and $(document).ready() functions
These three functions are the same:
$(document).ready(function(){
})
and
$(function(){
});
and
jQuery(document).ready(function(){
});
here $ is used for define jQuery like $ = jQuery.
Now difference is that
$(document).ready is jQuery event that is fired when DOM is loaded, so it’s fired when the document structure is ready.
$(window).load event is fired after whole content is loaded like page contain images,css etc.
From the jQuery API Document
While JavaScript provides the load event for executing code when a
page is rendered, this event does not get triggered until all assets
such as images have been completely received. In most cases, the
script can be run as soon as the DOM hierarchy has been fully
constructed. The handler passed to .ready() is guaranteed to be
executed after the DOM is ready, so this is usually the best place to
attach all other event handlers and run other jQuery code. When using
scripts that rely on the value of CSS style properties, it's important
to reference external stylesheets or embed style elements before
referencing the scripts.
In cases where code relies on loaded assets (for example, if the
dimensions of an image are required), the code should be placed in a
handler for the load event instead.
Answer to the second question -
No, they are identical as long as you are not using jQuery in no conflict mode.
The Difference between $(document).ready() and $(window).load() functions is that the code included inside $(window).load() will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the document ready event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.
$(document).ready(function(){
})
and
$(function(){
});
and
jQuery(document).ready(function(){
});
There are not difference between the above 3 codes.
They are equivalent,but you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $ as a shortcut name.
jQuery.noConflict();
jQuery.ready(function($){
//Code using $ as alias to jQuery
});
$(document).ready(function(e) {
// executes when HTML-Document is loaded and DOM is ready
console.log("page is loading now");
});
$(document).load(function(e) {
//when html page complete loaded
console.log("completely loaded");
});
The ready event is always execute at the only html page is loaded to the browser and the functions are executed....
But the load event is executed at the time of all the page contents are loaded to the browser for the page.....
we can use $ or jQuery when we use the noconflict() method in jquery scripts...
$(window).load is an event that fires when the DOM and all the content (everything) on the page is fully loaded like CSS, images and frames. One best example is if we want to get the actual image size or to get the details of anything we use it.
$(document).ready() indicates that code in it need to be executed once the DOM got loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.
<script type = "text/javascript">
//$(window).load was deprecated in 1.8, and removed in jquery 3.0
// $(window).load(function() {
// alert("$(window).load fired");
// });
$(document).ready(function() {
alert("$(document).ready fired");
});
</script>
$(window).load fired after the $(document).ready().
$(document).ready(function(){
})
//and
$(function(){
});
//and
jQuery(document).ready(function(){
});
Above 3 are same, $ is the alias name of jQuery, you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $. If u face conflict jQuery team provide a solution no-conflict read more.
$(window).load was deprecated in 1.8, and removed in jquery 3.0

JQuery ClueTip with ColdFusion - Javascript $(document).ready() misfire [duplicate]

Yesterday I had an issue where a .on('click') event handler I was assigning wasn't working right. Turns out it's because I was was trying to apply that .on('click') before that element existed in the DOM, because it was being loaded via AJAX, and therefore didn't exist yet when the document.ready() got to that point.
I solved it with an awkward workaround, but my question is, if I were to put a <script> tag IN the ajax loaded content and another document.ready() within that, would that second document.ready() be parsed ONLY once that ajax content is done being loaded? In other words, does it consider that separately loaded ajax content to be another document, and if so, does having another document.ready() within that ajax-loaded HTML work the way I think it does?
Alternatively; what would be a better way to handle this situation? (needing to attach an event listener to a DOM element that doesn't yet exist on document.ready())
To answer your question: No, document.ready will not fire again once a ajax request is completed. (The content in the ajax is loaded into your document, so there isn't a second document for the ajax content).
To solve your problem just add the event listener to the Element where you load the ajax content into it.
For example:
$( "div.ajaxcontent-container" ).on( "click", "#id-of-the-element-in-the-ajax-content", function() {
console.log($( this ));
});
For #id-of-the-element-in-the-ajax-content you can use any selector you would use in $("selector"). The only difference is, only elements under div.ajaxcontent-container will be selected.
How it works:
As long as div.ajaxcontent-container exists all elements (if they exist now or only in the future) that match the selector #id-of-the-element-in-the-ajax-content will trigger this click-event.
Javascript in the resulting ajax call will not be excecuted (by default) due to safety. Also, you can't directly bind event to non-existing elements.
You can bind an event to some parent that does exist, and tell it to check it's children:
$(document).ready(function(){
$(document).on('eventName', '#nonExistingElement', function(){ alert(1); }
// or:
$('#existingParent').on('eventName', '#nonExistingElement', function(){ alert(1); }
});
Always try to get as close to the triggering element as you can, this will prevent unnessesary bubbling through the DOM
If you have some weird functions going on, you could do something like this:
function bindAllDocReadyThings(){
$('#nonExistingElement').off().on('eventName', function(){ alert(1); }
// Note the .off() this time, it removes all other events to set them again
}
$(document).ready(function(){
bindAllDocReadyThings();
});
$.ajaxComplete(function(){
bindAllDocReadyThings();
});
try this, that is not working because your control is not yet created and you are trying to attach a event, if you use on event it will work fine. let me know if you face any issues.
$(document).ready(function(){
$(document).on('click', '#element', function (evt) {
alert($(this).val());
});
});
The answer here is a delegated event:
JSFiddle
JSFiddle - Truly dynamic
jQuery
$(document).ready(function(){
// Listen for a button within .container to get clicked because .container is not dynamic
$('.container').on('click', 'input[type="button"]', function(){
alert($(this).val());
});
// we bound the click listener to .container child elements so any buttons inside of it get noticed
$('.container').append('<input type="button" class="dynamically_added" value="button2">');
$('.container').append('<input type="button" class="dynamically_added" value="button3">');
$('.container').append('<input type="button" class="dynamically_added" value="button4">');
$('.container').append('<input type="button" class="dynamically_added" value="button5">');
});
HTML
<div class="container">
<input type="button" class="dynamically_added" value="button1">
</div>
I'm working on a code-base with a friend that has a similar requirement. The delegated event handler option is definitely best if all you want is to attach event handlers. An alternative, especially if you need to do other DOM processing in your $(document).ready function, is to put the code you want run into a script element at the end of your code. Basically, instead of:
<script type="text/javascript">
$(document).ready(function() {
// Your code here
});
</script>
<!-- rest of dynamically loaded HTML -->
Try swapping the script and the rest of the HTML around so you have:
<!-- rest of dynamically loaded HTML -->
<script type="text/javascript">
// Your code here
</script>
This forces the browser to only process your code once it has loaded every other DOM element in the dynamically loaded HTML. Of course this means you'll have to make sure the inserted HTML does not have unintended UI consequences by using CSS/HTML instead of JS. Its an old Javascript trick from years gone by. As a bonus, you don't need jQuery for this anymore.
I should mention that in Chromium v34, putting a second $(document).ready call inside a <script> tag in the dynamically loaded HTML seems to wait for dynamically loaded DOM to load and then runs the function as you described. I'm not sure this behaviour is standard though as it has caused me great grief when trying to automate tests with this kind of code in it.
JQuery AJAX .load() has a built-in feature for handling this.
Instead of simply $('div#content').load('such_a_such.url'); you should include a callback function. JQuery .load() provides room for the following:
$('div#content').load('such_a_such.url',
{ data1: "First Data Parameter",
data2: 2,
data3: "etc" },
function(){ $('#span1').text("This function is the equivalent of");
$('#span2').text("the $(document).ready function.");
}
);
However, you do not need to include the data argument.
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
http://api.jquery.com/load/

What is the best way to check if dynamic web pages are fully loaded?

I only need to check that the page is loaded (without dynamic objects that might be modified after page appears fully)
I know JQuery's function: "ready()"
Will this function be relevant in the described-above case?
Is there another / better way?
window.onload isn't a jQuery function, it's a DOM event.
If using jQuery the best way to check whether the page is loaded is to handle the ready event which can be done in various ways
Shortest
$(function() {
// DOM initialized
});
Short
$.ready(function() {
// DOM initialized
});
Longer
$(document).ready(function() {
// DOM initialized
});
Longest
jQuery(document).ready(function() {
// DOM initialized
});
Just to mention that you have an alternative to jQuery' methods . You can use pure JavaScript solution:
window.addEventListener("load", function load(event){ // defining load event listener
window.removeEventListener("load", load, false); //remove listener, no longer needed
// window is loaded , you can use its DOM
},false);
This way is good in cases when you , for example , have small/lightweight pages and to load external libraries/frameworks is absolutely unnecessary .

jquery functions dont work on dom elements loaded asynchromously

I wrote jQuery event handlers on DOM elements that are not yet in the page but might be loaded asynchronously into the page. What I observed was these event handlers seem to not recognize that some new elements were added to the DOM and that they need to act on them on triggering.
Am I right in my observation? How do I achieve this functionality?
If you want event handlers to work on dynamically added content, you need to use on
$(document).on("click", "someCssSelector", function(){
//your code here
});
Of course this will cause all clicks anywhere on your page to be watched. To be more efficient, see if you can structure your page so that all of these elements whose click event you want to handle will be in one container. ie, if all of these elements are going to be added to a div with an id of foo, you'd write the above more efficiently as
$("#foo").on("click", "someCssSelector", function(){
//your code here
});
If you're using jQuery < 1.7, you'd use delegate
$(document).delegate("someCssSelector", "click", function(){
//your code here
});
Am I right in my observation?
Yes.
How do I achieve this functionality?
Using the .on function to subscribe to those event handlers if you are using jQuery 1.7+:
$(document).on('click', '.someSelector', function() {
...
});
or using the .delegate function if you are using an older version (higher than 1.4.3):
$(document).delegate('.someSelector', 'click', function() {
...
});
For both you could use a more specific root than document to improve performance if you know that those elements will be added to some container for example.
And if you are using some prehistoric version you could go with .live():
$('.someSelector').live('click', function() {
...
});

How can I make ALL links load pages dynamically? (Even links in dynamically loaded pages)

So I have a script like this
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("a[href*='http://']:not([href*='"+location.hostname+"'])").attr("target","_blank");
$("a[target!='_blank'][target!='_top']").click(function(){
var url=$(this).attr("href")+'?jquery=1';
ajaxpage(url,'actualcontent');
window.location.hash=$(this).attr("href");
return false;
});
});
</script>
and it works great. It means all my links load dynamically within the DIV - awesome. But, the links loaded in those div, don't load dynamically when clicked. and if I include this script in it, it still doesn't work. And on a similar note, is there a way of making javascript in pages, which have been loaded dynamically, work? Without including it in the original header?
Thanks.
Disclaimer: To use this solution, you'll need to upgrade to jQuery 1.3 or jQuery 1.4+
(But you should, there are many performance improvements and bug fixes since 1.2.6)
Instead of .click() you can use .live() here, like this:
$("a[target!='_blank'][target!='_top']").live('click', function(){
.live() works on dynamically added elements as well, since it's listening for the bubbling click event at document, rather than being a handler on the element itself.
Not sure what your problem is. You are saying that the links that are added after this function rn do not use this function? hint, you need to rescan the page to update the links in that div OR you can avoid that and use live().
Use .delegate()
// Don't need to put this in a $(document).ready() callback.
$(document).delegate("a[target!='_blank'][target!='_top']", "click", function(e){
var url=$(this).attr("href")+'?jquery=1';
ajaxpage(url,'actualcontent');
window.location.hash=$(this).attr("href");
e.preventDefault();
return false;
});
$(document).delegate("a[href*='http://']:not([href*='"+location.hostname+"'])", "click", function(){
// lazy attr setting, reduces query cost
$(this).attr("target", "_blank")
});

Categories