Calling a function as soon as an element is encountered - javascript

Suppose I have an element on my page with id "some_id". I want to call a function as soon as I encounter this element. Something like following.
$("#some_id").call_a_function(function () {
// do stuff
});

Not sure what you mean by "encounter this element". If you mean as soon as the element is parsed, you could always inline some script right after it:
<div id="some_id">Hello</div>
<script type="text/javascript">
$("#some_id").call_a_function(function () {
// do stuff
});
</script>
The javascript code will be parsed right after the div. Of course, this wouldn't be much quicker than using $(document).ready() on small pages.

Checkout this jquery plugin as an alternative to $(document).ready()
http://plugins.jquery.com/project/available
Allows you to specify a handler to a DOM element as soon as it becomes available.

Related

Jquery Onclick functionality not working for div, as specific loaded after sometime

For <div class="editdiv">Test</div>. Jquery click functionality is added in document.ready function . But editdiv loading in page dynamically with delay.
So when I click on the div. Function is not calling. By using timeout function is working fine.
I need a different approach to solve this functionality.
If your .editdiv is loaded dynamically after your js loading so your click event can't detect it and it will not work, instead you should use event delegation on() to deal with fresh DOM :
$('body').on('click', '.editdiv', function(){
//Your click event code
})
If you want to avoid setTimeout you could use delay with queue callback method :
$('div.scroll-area-blue')
.delay(5000)
.queue(function() {
$(this).enscroll({
showOnHover: false,
verticalScrolling: true,
verticalTrackClass: 'vertical-track-blue',
verticalHandleClass: 'vertical-handle-blue'
});
});
If you will use setTimeout better to use it like :
setTimeout( enscrollDiv, 5000);
function enscrollDiv(){
$('div.scroll-area-blue').enscroll({
showOnHover: false,
verticalScrolling: true,
verticalTrackClass: 'vertical-track-blue',
verticalHandleClass: 'vertical-handle-blue'
});
}
Hope this helps.
It is really difficult to understand whats going wrong from your question. What I guess is you are loading a specific div using Ajax or similar technologies - meaning the div is not available initially.
The way jQuery works is that, it only binds the event to the elements only available at the time the part is executed.
If a <div id='myDiv'></div> is not present when $('#myDiv').click(function(){}) is called, it won't work.
One workaround is to do it like this:
$('body').on('click','#myDiv',function(){});
This registers the click on body and then checks if the clicked element is having a id 'myDiv' or not. We can expect the <body></body> to be present always. So the problem we had with previous code won't happen here.
maybe you're loading the javascript codes before the html elements(tags) are loaded.
try adding the script which includes "document.ready()" before the end tag of the body when all html tags have already finished loading.
I'm hitting targets in the dark. Hope it works for you. It's difficult to generate any solution without analyzing the problematic code......

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/

Javascript Functions, Ready, Click, Each, Next, This, and Toggle

I just started learning web development and someone gave me this code to use. However, I want to understand it so that I can change it the way that I would like. However, I am having some trouble understanding it completely. I have the basics of computer programming. I just am having a hard time understanding what this code here is doing. I've done some research here https://api.jquery.com/. I understand the individual concepts kind of, but can't put them together. So here is what I understand so far:
.ready(): It makes sure that the page is loaded and is ready for use. And I'm assuming the following code won't execute unless the page is fully loaded and ready for interaction.
.click(): Basically responds to a click.
.each(): Kind of a like a for loop.
.next(): Goes to the next element.
.hide(): Hides the element (which is kind of confusing, because it doesn't actually hide it, it just makes it jump up)?
.toggle(): It reveals a hidden element?
Here is the code:
$(document).ready(function(){
$('.info').click(function(){
$('.info').each(function(){
$(this).next().hide();
});
$(this).next().toggle();
});
});
I think that's it. But I'm not sure how it all fits in. Could someone please explain it to me?
Also, why doesn't the code above work without this line:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
The line
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
loads the jQuery library from the CDN URL above. This Javascript file contains the definition of all the above functions you're using as well as many other useful functions. You can read more on the official docs. https://api.jquery.com/
Code Explanation
$(document).ready(function () {
This registers a ready event on document. In other words, the callback anonymous function is called when the DOM is completely loaded and is ready to be manipulated.
$('.info').click(function () {
Just like the ready event handler, this code binds a click event on all the elements having class of info.
$('.info').each(function () {
$(this).next().hide();
});
This part of code will loop over all the elements having the class of info and hides the next element of each element one by one.'
$(this).next().toggle();
This will toggle the visibility of the next element of the clicked-$(this) element. Not really, this is showing the next element as in the above each loop, you've hide all the next elements of .info class.
}); // End of click
}); // End of ready
Your code can also written without loop as
$(document).ready(function () {
$('.info').click(function () {
$('.info').not(this).next().hide();
// Hide all elements that are nextSibling of the elements having class info other than the clicked one
$(this).next().show();
// Show the next element of the clicked element
});
});
First of all, you should know js is a language, and most of the functions you mentioned here are jQuery functions.
jQuery is a library written in js which has a lot of functions and options to support development.
So the line of script you included, loads the jQuery library in to the page.
As for the other questions:
.ready(): It makes sure that the page is loaded and is ready for use. And I'm assuming the following code won't execute unless the page is fully loaded and ready for interaction.
As you wrote - this is a function to deal with page loading, although the following code will execute before page is done loading, and that is because js is a non-blocking script
so the proper use of .ready() is:
$(document).ready(function(){
....//all code you need after page is fully ready goes here
});
.click(): Basically responds to a click.
Correct. this responds to a DOM event of a DOM element. It is really impotent to understand what is DOM and how to use it when developing for web.
$(element).click(function(){
....//all code you need after clicking element goes here
});
.each(): Kind of a like a for loop.
Correct. this loops through DOM elements, and in each iteration you get a reference to the current one
$(elements).each(function(){
var element = $(this) //jquery wrapper of current iterated DOM element. this refers to current iterated DOM element
});
.next(): Goes to the next element.
this is a way of "walking" through the DOM tree, to manipulate elements in it
.hide(): Hides the element (which is kind of confusing, because it doesn't actually hide it, it just makes it jump up)?
this does actually hide the element. This would probably be done using css to hide the element
.toggle(): It reveals a hidden element?
this is a shortcut for hide() and show(). It checks if element is hidden, and if it is, it uses show(), otherwise, it uses hide(). as mentioned, this would also probably be done with css

how to use jquery in included html?

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")

how can i invoke a function after page is done loading? (and only then..)

I'm having trouble with some jquery code.
in my HTML page I use ajax to get some info, and then I'm changing an HTML element
with $("#id").html(...).
The problem is, I also have a $(document).ready code which I wanna call only once
when the page is done loading, but after each change in the html with the $("#id").html(...)
the code is called once again.
How can I run the $(document).ready code only once?
Here is an example:
$(document).ready(function(){
// this code will run not only once...
}
function f(){
$("#id").html(...);
}
Try:
var run = false;
$(document).ready(function() {
if(!run) {
...
run = true;
}
});
...or...
$(window).load(function() {
...
});
The first one will make sure it is only run once; the 2nd one is run when the entire page is finished loading (useful if you need to resize things once images have finished loading).
From the comments on the .ready documentation:
Looks like .ready() fires not only when page initially has settled the
DOM, but apparently also after changes to the DOM. This is an issue if
your ready handler changes the DOM. That will result in ready() firing
more than once. It may result in an endless loop if each invocation
adds yet more to the DOM. Firefox and IE behave differently to this,
including different error messages, and leaving the page display in
different states. So, if ready() modifies the DOM, then it would be
wise to have a way to check whether ready has already been fired.
Replying to self: Well it appears that part of the problem is not that
the ready function fires again (though that is possible aparently),
but that changing the DOM causes the script that creates the ready
function to fire again, adding an additional ready function, etc etc.
This seems to happen if the javascript is embedded in the html at a
point beyond (or contained in) the part of the DOM that the ready
handler modifies. (Obviously would be better to put script that
creates a ready function in the document head, but in this case that's
not an option.) Problem fixed by checking a global flag variable to be
undefined before executing jQuery(document).ready(...).
If this might be your problem, you can adopt the same solution:
var onLoadFired = false;
$(document).ready(function() {
/* Ensure this function only runs once */
if (onLoadFired) {
return;
}
else {
onLoadFired = true;
}
/* Business logic */
// .. your code here ..
});
Or, better, move your handler into a separate script file that's included by a script tag in your page's head element.
Try this:
$(window).bind("load", function() {
...
});

Categories