jquery .load isn't checking if my element is loaded - javascript

I have this code
<script type="text/javascript">
$("#main_photo_display").load(function(){
alert("loaded");
});
</script>
<div id="main_photo_display"></div>
I need it to do something once that div has loaded. Currently it does nothing. When I substitute window for "#main_photo_display" it works. I have googled and I keep coming across .load as how to check if a page element has been loaded.

The load event is sent to an element when it and all sub-elements have
been completely loaded. This event can be sent to any element
associated with a URL: images, scripts, frames, iframes, and the
window object.
Source: http://api.jquery.com/load-event/
Further down on the same page they state:
It doesn't correctly bubble up the DOM tree
So you can't delegate this event, the event handler must be attached to the element on which the load event fires.

Or you can run the script after the DOM is ready like so:
<script type="text/javascript">
$(document).ready(function() {
$("#main_photo_display").load(function(){
alert("loaded");
});
});
</script>
<div id="main_photo_display"></div>
Sorry I think I read it wrong :) You need this:
<script type="text/javascript">
$(document).ready(function() {
alert('loaded');
});
</script>

A plain div does not have a load event except when you are loading content into it with ajax (which I don't think is what you are doing here). If your code is physically located after the div in your page, then the div will be available and ready for your code to operate on it (you don't have to check anything).
If your code is located before the div in the page, then you can use jQuery's .ready() method to know when it is safe to access the div:
<script type="text/javascript">
$(document).ready(function() {
// safe to access $("#main_photo_display") here
});
</script>
<div id="main_photo_display"></div>

I don't think a DIV fires a loaded event. If there was a blank.gif image within the DIV, you could attach the $.load() function to that.
<div id="main_photo_display">
..... Other Content .....
<img class="loadcheck" src="blank.gif" width="0" height="0" />
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#main_photo_display img.loadcheck").load(function(){
alert("loaded");
});
});
</script>

You can't do that: load events are not fired on just any HTML element, only on those that require loading an external resource.
The best way to ensure the element is loaded is to put the script tag after it in the markup.
<div id="main_photo_display"></div>
<script type="text/javascript">
alert("loaded");
</script>
The Javascript will not be run before the div is parsed.

I have a sort of workaround, and it is sloppy (please comment out if you have notes).
It is useful when you have a javascript out of your control which appends elements to your dom on a page load.
$(function () {
var counter = 0;
var intervalId = setInterval(function () {
$(document).mouseover()
}, 105);
var unbind = function () {
$(document).off('mousemove', '#label');
$(document).off('mouseover');
window.clearInterval(intervalId);
};
$(document).mouseover(function () {
$('#label').trigger('mousemove');
counter++;
if (jivositecounter > 200) unbind();
});
$(document).on('mousemove', '#label', function () {
console.log(counter);
...doing our stuff when #label appears
unbind();
});
});

Related

Proper way to add onload function to body using jQuery

On one of my previous pages I use
<script src="/js/wireEvent.js"></script>
<body onload="wireEvent();" >
Basically, wireEvent() displays an image on top of the page whenever the mouse goes out of the browser.
However, now I cannot add this function directly to the body of my page, so what is the proper way to add it? Will it be right if I add
<script>
window.onload = wireEvent;
</script>
or I enclose the whole function in
$( document ).ready
and only include the function's file to my html?
The code below executes only after all your images load completely. So you can try this:
$(document).on('load', function(){
wireEvent();
});
You can just do:
$(function(){
//jQuery code here
});

how can fire event after end loading nested html page (page in object )

i want hide object after html page end loading not the man html tag
this is my code
$('<div id="content" ><object data="../06.html"></div>').appendTo('section')
i try use load but return after div loading i don't want this
With jQuery, you can start some action after the DOM is loaded. The content (e.g. images) isn't necessarily already there, but you can manipulate every DOM element after the DOM is ready. Use the following snippet for that:
$(document).ready(function() {
//some code
});
If you want to wait until the page is fully loaded (e.g. also images), you can use window.onload:
window.onload = function() {
//some code
};
To hide a <div> when your webpage is fully loaded:
$(window).load(function () {
$('div').fadeOut(); //or .hide()
});
To show a div when the page is fully loaded:
$(window).load(function (){
$('div').fadeIn(); //or show()
});
If that's not what you're looking for, then please do explain more about your problem.

Sidebar Toggle doesn't work despite of the inline javascript

I'm developing a template. While doing so, i encountered a error. I have placed a button that toggles the sidebar from invisible to visible state.I have used the right codes to initiate the jquery response.But the sidebar doesn't toggle.Help me solve this issue
html
<a id="click-slide">
<span>
\
</span>
</a>
Javascript
<script type="text/javascript">
//<![CDATA[
$("#posts-container,a#click-slide").click(function() {
$("#topbar #category").removeClass("category-list-move")
});
$("a#click-slide").click(function() {
$("#sidebar").toggleClass("sidebar-move");
$("#topbar").toggleClass("topbar-move");
$("#posts-container").toggleClass("posts-container-move")
});
//]]>
</script>
My site
i have used it with and without Cdata.Where did i go wrong
You should put your javascript code into document.ready. The reason behind document.ready is you put your javascript code before the a#click-side element. That means when your javascript executed, in the page there is no element called a#click-side. When we put into document.ready it downloads your javascript and all document gently and then starts executing your javascript code.
<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){
$("#posts-container,a#click-slide").click(function() {
$("#topbar #category").removeClass("category-list-move")
});
$("a#click-slide").click(function() {
$("#sidebar").toggleClass("sidebar-move");
$("#topbar").toggleClass("topbar-move");
$("#posts-container").toggleClass("posts-container-move")
});
});
//]]>
</script>
You've not wrapped your code in a document.ready event handler. Change it to this...
jQuery(function($) {
$("#posts-container,a#click-slide").click(function() {
$("#topbar #category").removeClass("category-list-move")
});
$("a#click-slide").click(function() {
$("#sidebar").toggleClass("sidebar-move");
$("#topbar").toggleClass("topbar-move");
$("#posts-container").toggleClass("posts-container-move")
});
});
It was trying to assign the click event handlers before the page was loaded, so none of the elements actually exist at that time. Wrapping in the ready handler, as above, means it will only run the script when the page has finished loading.
Added your code when document gets ready.
<script type="text/javascript">
$(document).ready(function(){
$("#posts-container,a#click-slide").click(function() {
$("#topbar #category").removeClass("category-list-move")
});
$("a#click-slide").click(function() {
$("#sidebar").toggleClass("sidebar-move");
$("#topbar").toggleClass("topbar-move");
$("#posts-container").toggleClass("posts-container-move")
});
});
</script>

Detect click event inside iframe

I'm writing a plugin for TinyMCE and have a problem with detecting click events inside an iframe.
From my search I've come up with this:
Loading iframe:
<iframe src='resource/file.php?mode=tinymce' id='filecontainer'></iframe>
HTML inside iframe:
<input type=button id=choose_pics value='Choose'>
jQuery:
//Detect click
$("#filecontainer").contents().find("#choose_pic").click(function(){
//do something
});
Other posts I've seen usually have a problem with different domains (this hasn't). But, still, the event isn't detected.
Can something like this be done?
I solved it by doing like this:
$('#filecontainer').load(function(){
var iframe = $('#filecontainer').contents();
iframe.find("#choose_pics").click(function(){
alert("test");
});
});
I'm not sure, but you may be able to just use
$("#filecontainer #choose_pic").click(function() {
// do something here
});
Either that or you could just add a <script> tag into the iframe (if you have access to the code inside), and then use window.parent.DoSomething() in the frame, with the code
function DoSomething() {
// do something here
}
in the parent.
If none of those work, try window.postMessage. Here is some info on that.
$("#iframe-id").load( function() {
$("#iframe-id").contents().on("click", ".child-node", function() {
//do something
});
});
I know this is old but the ID's don't match in your code one is choose_pic and one is choose_pics:
<input type=button id=choose_pics value='Choose'>
$("#filecontainer").contents().find("#choose_pic").click(function(){
//do something
});
The tinymce API takes care of many events in the editors iframe. I strongly suggest to use them. Here is an example for the click handler
// Adds an observer to the onclick event using tinyMCE.init
tinyMCE.init({
...
setup : function(ed) {
ed.onClick.add(function(ed, e) {
console.debug('Iframe clicked:' + e.target);
});
}
});
Just posting in case it helps someone. For me, the following code worked perfect:
$(document).ready(function(){
$("#payment_status_div").hide();
var iframe = $('#FileFrame').contents();
iframe.find("#take_payment").click(function(){
$("#payment_status_div").show("slow");
});
});
Where 'FileFrame' is the iframe id and 'take_payment' is the button inside iframe. Since my form inside the iframe is posted to a different domain, when used load, I got an error message saying:
Blocked a frame with origin "https://www.example.com" from accessing a frame with origin "https://secure-test.worldpay.com". Protocols, domains, and ports must match.
In my case there were two jQuery's, for the inner and outer HTML. I had four steps before I could attach inner events:
wait for outer jQuery to be ready
wait for iframe to load
grab inner jQuery
wait for inner jQuery to be ready
$(function() { // 1. wait for the outer jQuery to be ready, aka $(document).ready
$('iframe#filecontainer').on('load', function() { // 2. wait for the iframe to load
var $inner$ = $(this)[0].contentWindow.$; // 3. get hold of the inner jQuery
$inner$(function() { // 4. wait for the inner jQuery to be ready
$inner$.on('click', function () { // Now I can intercept inner events.
// do something
});
});
});
});
The trick is to use the inner jQuery to attach events. Notice how I'm getting the inner jQuery:
var $inner$ = $(this)[0].contentWindow.$;
I had to bust out of jQuery into the object model for it. The $('iframe').contents() approach in the other answers didn't work in my case because that stays with the outer jQuery. (And by the way returns contentDocument.)
If anyone is interested in a "quick reproducible" version of the accepted answer, see below. Credits to a friend who is not on SO. This answer can also be integrated in the accepted answer with an edit,...
(It has to run on a (local) server).
<html>
<head>
<title>SO</title>
<meta charset="utf-8"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<style type="text/css">
html,
body,
#filecontainer {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<iframe src="http://localhost/tmp/fileWithLink.html" id="filecontainer"></iframe>
<script type="text/javascript">
$('#filecontainer').load(function(){
var iframe = $('#filecontainer').contents();
iframe.find("a").click(function(){
var test = $(this);
alert(test.html());
});
});
</script>
</body>
</html>
fileWithLink.html
<html>
<body>
SOreadytohelp
</body>
</html>
In my case, I was trying to fire a custom event from the parent document, and receive it in the child iframe, so I had to do the following:
var event = new CustomEvent('marker-metrics', {
detail: // extra payload data here
});
var iframe = document.getElementsByTagName('iframe');
iframe[0].contentDocument.dispatchEvent(event)
and in the iframe document:
document.addEventListener('marker-metrics', (e) => {
console.log('#####', e.detail);
});
try
$('#yourIframeid').on("load", function () {
$(this).contents().on("contextmenu, keydown, mousedown, mouseup, click", function (e) {
//do your thing
});
});
use $('#yourIframeid').on("load") if $('#yourIframeid').onload( does not work.

Inserting javascript in to html file

How can I run this script, tried to run it in html file, but it doesn't seem to work..
I want this code to be in single html file, is it possible? or do I need different files?
http://jsfiddle.net/ambiguous/jcnMa/1/
<script type="text/javascript">
$('.question, .answer')
.css("display", "none");
$('.section')
.click(function ()
{
var $others = $('.question:visible')
.not(this);
$others.next('.answer')
.hide();
$others.slideToggle(500);
$(this)
.next('.question')
.slideToggle(500);
});
$('.question')
.click(function ()
{
$(this)
.next('.answer')
.slideToggle(500);
});​
</script>
First make sure you're including the jQuery library:
<script src="path/to/jquery.min.js"></script>
Make sure you're not including the jQuery within those tags, so you've got:
<script src="path/to/jquery.min.js"></script>
<script>
/* Your jQuery here */
</script>
And then ensure you're using a $(document).ready(), or $(window).load(), handler:
<script src="path/to/jquery.min.js"></script>
<script>
$(document).ready(
function(){
/* Your jQuery here */
});
</script>
The requirement for the $(document).ready() (or $(window).load()) is to ensure that the DOM is constructed, and the elements to which you want to bind events are present. Without those handlers the browser will try to bind events as soon as it encounters your script, without waiting for the elements to exist or be created, which results in non-functioning event-binding.
put this code before the body close tag
Your Code
</body>
I would go this way:
<head>
...
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.question, .answer').css("display", "none");
$('.section').click(function ()
{
var $others = $('.question:visible').not(this);
$others.next('.answer').hide();
$others.slideToggle(500);
$(this).next('.question').slideToggle(500);
});
$('.question').click(function ()
{
$(this).next('.answer').slideToggle(500);
});​
});
</script>
...
</head>
First you need to ensure jquery lib is loaded, then you might notice that your code is referring to object in DOM, so you can access them only when the page is loaded (or after they are entered in the body code). I prefer to store my js code in the head section whenever it's possible.

Categories