JavaScript will not run a second time - javascript

I am running a script using $(document).ready() it is performing the way I want it to on load up, however, the same script needs to be ran when an html select control is changed.
What I need ultimately is for the filter and sort to run on initial load with sorting on Low to High, and then after the page is loading the user should be able to select any select control and filter and sort as they wish.
Go to http://webtest.ipam.ucla.edu to view the code and on the bottom of the page you can download the folder with all of the files.
How do I fix this?

You can put all your reusable logic into a function:
function myPrettyJavaScriptLogic () {
// All the code that you want to reuse in here
}
Then you can call the above function both from document.ready() and also from the onchange handler of your select control.

Create a function outside of your doc ready closure and call it when you need to. Example is jQuery but doc ready is the same event:
var doSomethingCool = function( coolStuff ) {
// Do cool stuff
}
$(function(){
doSomethingCool( $(this) );
$('#selectControlId').change(function(e){
doSomethingCool();
});
});

Since you are referencing the .ready function I'm assuming you are actually using jQuery.
$(document).ready() or jQuery(document).ready()
Anything within the ready() function will only be called once - when the page is loaded. It waits until the entire DOM is loaded before executing that code.
You can extract out your functionality to a separate function to get kicked off based on your select control changing.
You may benefit from reading a jQuery tutorial I wrote the other week:
http://chadcarter.net/jquery-goodness/
Also, the actual .change event in the jQuery API is here:
http://api.jquery.com/change/
Assuming you want the functionality to be called when the page loads and when the option is changed you will want to create a new function and have that function called inside of both the .ready and the .change functions.
Hope this helps!

put your script in a Named function. call it in domready and select.change().

You will need to set up a handler for the select box's onChange event. What I would do is pull out the code you need to execute into a separate function and then do something like
function dostuff(){
//do whatever you need to
}
$(document).ready(function() {
dostuff();
}
<select onchange"dostuff()" >... </select>
Note this was quick and dirty, just to give you an idea.
Check out this link for more about select's onchange.

If you are using jQuery, which I will assume you are because of this syntax, you just have to bind the event onchange to the element.
$("element").bind("change", function() { /* your logic */ });
You have to run this code after the element is rendered. If you place this code inside the $(document).ready there will be no problem. but the whole page will have to load before the even is bound.
So you can do the following:
<select id="sel">
<option>A</option>
<option>B</option>
</select>
Then bind the event change.
$(function() { /* equivalent to document.ready */
$("#sel").bind("change", function() {
/* code that runs when the selection change */
});
});

Thank you all for your help, this is now fixed. The way i did it was to encapsulate the $(function(){}) in another function (filtersortProcess()) and then created another script that autoselects the Low to High option and calls filtersortProcess() on windows.load.
Within the $(function(){}) I added a variable (complete) and set it to 1 when it goes within the actual filter process, then after the filter process (if the code exits before completing the process) I check for the complete variable and do a simple filter and sort on the data and with all of this it works great.
Thank you again.

Related

How to prevent multiple event calling with jQuery on change

The problem is that sometimes on select change $('selector').on('change', ...) function is fired multiple times.
Generally when I'm using .on function then I always add .off() function and it works great. But in this case I can't use the off function due to the fact that off function is disabling the select input (I mean that it does not change).
I've tried to add event.preventDefault() and event.stopImmediatePropagation() but it is not the solution.
JS:
$('#addMealToMenuDiet').on('change', function(event) {
//then ajax function is called
});
HTML:
<select id="addMealToMenuDiet" class="form-control">
...
</select>
How can I avoid such a situation?
Solution
Unfortunately my on change method was placed in another on click method. Therefore it was called multiple times...
most possibly your code runs multiple times, you could simply always unbind the event before you bind it just put your ajax stuff into a function in before your other code
function myAjaxfunction(){
//...
}
and then run this to initialize your select
$(document).off("change", '#addMealToMenuDiet', myAjaxFunction).on("change", '#addMealToMenuDiet', myAjaxFunction)
this way you are on the save side ;)

is there a way to run the jquery.live function without any event

The live function of jQuery is triggered with an event
The api documentation is here
http://api.jquery.com/live/
$(".xyz").live('event', function(){
});
I want the above function to run without an event , i.e as soon as the class xyz is dynamically created.
I have tried this without the event parameter
$(".xyz").live( function(){
});
but it doesn't work !!
adding
I don't know exactly what you want to do, but I'll make assumptions.
Scenario 1
In order to execute a function inside jQuery, you need to tell jQuery when to execute the function, otherwise it cannot know. One way to do this is:
$(document).ready(function () {
$('.xyz').css('color', 'red');
// more code, anything, functions, calculations, etc.
});
The code inside that function will be executed as soon as your DOM is ready (is safe to manipulate).
You can put $('.xyz').css('color', 'red'); also outside the ready() event and it will also be executed. The "event" this time is when the executions of the page reaches that line of code. For example, if you put this line before your HTML, you don't have guarantee it will work.
Scenario 2 - onClassChange event
If you are looking for an event called something like onClassChange, it does not exits on jQuery. An approach to that problem could be this:
Create a timer which runs infinitely
On each run, check if that object has your class ( $(obj).hasClass('xyz') )
If yes, do whatever you want to do inside the if ()
Also, since you said the class xyz is created dynamically, you can try to run your function immediately after you create your class in your code.
For more about onClassChange event, there are long discussions you can check on this site.

jquery load / get and dom elements not triggering...?

I'm loading a simple page using:
$.get('../admin/login.php', function(data) { $('#box-contents').html(data); });
Now, on this login.php page I have an input field, and in my global JavaScript file, I have an event that triggers on .change() - but this isn't firing!?
Is this because I have loaded this file on the page so jquery doesn't know that it's now there? Do I need to also include my global JS file within the 'login.php' page too?
Any help on this would be much appreciated
instead of using .get(), use .load() as it was intended for this purpose. Also for your .change() event, you need to either attach it after the element exists (which could be done in your callback below), or you can use .live() to attach the event to any current or future DOM elements.
Callback method
$('#box-contents').load('../admin/login.php', function() {
$('input').change(function() {
//do stuff on change
});
});
Live method
$('input').live('change', function() {
//do stuff on change
});

jQuery scripts no longer run on partially refreshed elements

I have a number of jQuery scripts that select elements within the area that I run a partial page refresh on.
I am using this css tricks code snippet to refresh that part of the page:
$('#refreshbutton').click(function() {
var url = "http://myUrl.com/indexTest.php?ID=" + Math.random();
setTimeout(function() {
$("#maindisplay").load(url+" #maindisplay>*","");
}, 100);
});
The problem is that the elements within #maindisplay are changed, thus are considered new elements in the dom. Since the scripts that select those elements and attach functions to them run at domready and not during the partial refresh, this poses a problem.
So far I have been unable to find a way to reattach the scripts to the elements within #maindisplay after I partially refresh it.
My question is: What is the optimal way to reattach the scripts to the refreshed area of the page.
Thank you for any advice.
You need to use the live() function to attach your click handler.
You have the following options that I can think of:
Put the attach in a function and call that function on page refresh
Use the .live() functionality
Use .delegate() functionality
Put the Javascript reference to the functionality in a reference in the refresh so that it executes as a part of that refresh
Put the function in the callback
make it part of your setTimeout
some other creative method I did not think of...
Just a note: I would look at the .delegate() with contextual selection added in recent versions (available in 1.4.2 for instance).
Does load() not take a callback function as it's second argument? Why not reattach event handlers to the elements with that function?
$('#result').load('ajax/test.html', function() {
//reattach event handlers here.
});

second $(document).ready event jQuery

I'm using some external jQuery with $(document).ready() to insert adverts after the document ready event has fired, something like:
$(document).ready( function() {
$('#leaderboard').html("<strong>ad code</strong>");
});
This is to prevent the UI being blocked by the slow loading of the adverts. So far it's been working well.
Now I need to insert some more ads though our CMS system, this can't be part of the external JS file, so I'm wondering can I use a second document ready event and insert it using an inline script tag? If so, what will be the order of execution the external JS document ready event first or the inline script?
You can use as many event methods as you want, jquery joins them in a queue. Order of method call is same as definition order - last added is last called.
A useful thing may be also that, you can load html code with script using ajax and when code is loaded into DOM $().ready() also will be called, so you can load ads dynamically.
Yes, adding multiple $(documents).ready()s is not a problem. All will be executed on the ready event.
Note however that your code sample is wrong. $(document).ready() takes a function, not an expression. So you should feed it a function like this:
$(document).ready( function() {
$('#leaderboard').html("<strong>ad code</strong>");
});
That function will be executed when the document is ready.
Here's a little tutorial on Multiple Document Ready
An added bonus of the jQuery way is
that you can have multiple ready()
definitions. This is the case with all
jQuery events.
$(document).ready(function () {
alert("Number One"); });
$(document).ready(function () {
alert("Number Two");
JQuery calls the ready functions in the order they are defined.
If you want to load some data first and deleay execution use holdReady().

Categories

Resources