Nicest way to run some JS immediately after an element has loaded? - javascript

Let's say you've got some HTML,
<input id="mytextbox" type="text" value="hello world" />
And you want to do some magic on that textbox as soon as it's loaded. Maybe add some kind of widget, or button beside it, whatever. There's 2 ways of doing this that I'm aware of. You can throw some jQuery like this in the <head>
$(function() {
$('#mytextbox').magic();
});
And that'll run once the entire DOM is ready, but what if we want it sooner? As soon the element has loaded?
We can put the JS immediately after the element:
<input id="mytextbox" type="text" value="hello world" />
<script>
$('#mytextbox').magic();
</script>
But that's a bit messier, and why should we have to search the entire DOM for an element ID when we know exactly where it is? onclick events have a this argument. Isn't there some way we can do something like this...
<input id="mytextbox" type="text" value="hello world" onload="$(this).magic()" />
? Would be nicest solution IMO, but only the body has an onload event apparently, and no other event seems suitable. Are we basically left to solution #2 if we want some piece of code to run immediately after an element is loaded?

Actually, your second snippet is the "best" (whatever that means, probably fastest) way to apply some Javascript to an element.
<input id="mytextbox" type="text" value="hello world" />
<script type="text/html">
$('#mytextbox').magic();
</script>
You are not searching the entire DOM here. A call like this directly goes down to
document.getElementById('mytextbox');
which is more or less, just insta-access to the node.
Anyway, a practice like this betrays the idea of unobtrusive Javascript. I wouldn't know a reason why you shouldn't apply some code when the DOMContentLoaded event fires (which is abstracted away by jQuerys .ready()).

Since javascript includes are generally blocking (unless you load it async ofcourse), it is always a good idea to put your javascript as low as possible on the page. That way the user won't have to wait for your javascript to load while browsing through the page.
So the question here is, do you really want it to load immediately after that element. Or simply at the bottom of the page.

Related

jQuery document.ready() not firing for dynamically loaded content

I've got a PHP file (called aboutMe.php) that contains some HTML as follows:
<script type="text/javascript" src="/aboutMe.js"></script>
<div id="aboutme-gender" class="aboutme-block">
<div class="aboutme-question">My gender is:</div>
<div class="aboutme-error">Please select your gender.</div>
<div class="aboutme-answer">
<input id="gender-male" name="the-gender" type="radio" value="1" />
<label for="gender-male">Male</label>
<input id="gender-female" name="the-gender" type="radio" value="2" />
<label for="gender-female">Female</label>
</div>
</div>
The aboutme.js file contains a function as follows:
jQuery(document).ready(function($) {.....does stuff to the tags in the HTML});
This all works fine if the page is loaded directly. However when another page wants to load this dynamically as follows:
$("#load-aboutme-here").load("aboutMe.php");
...the document.ready() event doesn't fire and things don't get tagged.
I've seen similar posts but can't quite get what I need from them. Have done things like substitute the document.ready() for window.load() but then it doesn't even work at all when the aboutMe.php page is loaded directly.
Any ideas much appreciated - this is driving me nuts although I suspect it's an easy fix!
Thanks
Iain
Note that the document is the main page...not subsequent files you retrieve
The document was ready long before the ajax is done so any $(document).ready() that is called after it is ready will fire immediately. In your case it will fire before the elements exist
Move the script tag below the html that the code is referencing
<div id="aboutme-gender" class="aboutme-block">
.......
</div>
<script type="text/javascript" src="/aboutMe.js"></script>
If I understood your problem correctly, I believe you could just create a callback for the .load() function like so:
$("#load-aboutme-here").load("aboutMe.php", null, function()
{
// Code to be executed when aboutMe.php is loaded.
// i.e. The code in aboutMe.js
});

Automatically click using onload?

How can I automatically click on an object using onload() with HTML.
Here's the button I would like to be automatically clicked:
<input type="button" value="{$LANG.checkout} »" class="checkout" onclick="addtocart();" />
What I would like to happen is for the button to be clicked automatically; as soon as a certain div is loaded. I know it's possible to do with Javascript, but is there any way to do it without javascript? If javascript is the only way I am more than open to it!
As a comment says, is not need to 'trigger a click automatically', just add the functionality in a script tag (or even better, in a separate file):
HTML
<input type="button" value="{$LANG.checkout} »" class="checkout" />
JS
<script>
addToCart();
function addToCart(){
//your code here...
};
</script>
Include this tag before the tag </body> (where body finish) and it will be execute when all your HTML (DOM) be ready.

javascript in iframe won't work

I have a website with lots of code, so obviously something is wrong, but I can't post all the code here. Here's the exact code I'm trying to use though.
Parent document...
<iframe name=combosIframe id=combosIframe src=getCombos.php style='position:absolute;left:300px;top:0px;width:275px;height:520px;overflow-y:scroll;overflow-x:hidden;border:1px solid black'></iframe>
<form name=colorForm id=colorForm action=colorCombos.php method=post target=combosIframe>
<input type=submit id=submitColors value=SubmitColors>
</form>
Inside the iframe, colorCombos.php page...
<script language=JavaScript>
alert('load');
function doSomething(){
alert('hi');
}
</script>
<form>
<input type=button value=ClickMe onClick=doSomething()>
</form>
Scenario: I click the parent form button to load the new page into the iframe.
Problem: the JavaScript in the colorCombos.php page does not alert, either on page load, or when clicking the button. If I view the page on its own it works fine.
Specs: php5, using Chrome browser.
Of note: there are no errors when I view the javascript console. Also there is nothing else on the colorCombos.php page. Both files are in the same directory. Thanks for any help, I'm really stumped.
Not using quotes within HTML Attributes can have undesired effects. Try adding quotes around all the values of each HTML Attribute.
Example:
<input type="button" value="ClickMe" onClick="doSomething()"/>
I started with a blank setup (which was working) copied the code from my site (which has lots of other code), bit by bit into the new document to see when the script stopped working. I ended up copying EVERYTHING (literally ctrl+a) into the new document, and it worked fine. I then renamed the new document to be the name of the old document, and it STOPPED working. The old document (i.e. the parent document) is named rangeTool.php, not that I think that is relevant necessarily.
So I have a solution, but not an answer. What in the world could cause one document to not work? Something wrong on the server? I deleted the old file off the server and loaded the new copy, but that didn't work as long as the name was rangeTool.php. For example, I renamed it testcode.php and it worked fine.
I'm still interested in why/how this happened, but at least the pressure is off now that it's working for me.

Passing a textfield value from one html page to another

My question may sound naive, but really struggling to do a very simple thing. Suppose I have to html page - send.html and receive.html.
In send.html page -
I have text field and a button in like following -
<body>
<form onsubmit="recieve.html">
<input type="text" id="mytextfield">
<input type="submit" id="submitbutton" value="Go">
</form>
</body>
Here I want to put something on the textfield and I want to see that value in the receive page some thing like - Hello 'value of textfield'. That's it.
Do I need to use JS cookie for that? If not, how can I do it in the most simple way?
Need help :(
The most simple way is PHP. Bottom line is you need something handling the data on the server side.
With javascript you can write a function to store the value in a cookie and read it on the next page. By the way, your page goes in the action attribute. onsubmit expects a javascript function, not a page.

Why the onload focus doesn't work on this script?

This is a sample of my form. when the page loads the focus must be on 'fbox' but it dosent work and i don understand why. the form contains a niceditor but i dont think that is the problem
<html>
<head></head>
<body onload="document.form.fbox.focus();">
<body>
<form method='post' action='' name='form' >
Headline <input name='fbox' type='text' class='form' id='box' autocomplete='off' size='80'><br>
Your text</font><br><script type="text/javascript" src="nicEdit.js"></script><script type="text/javascript">bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });</script>
<textarea name="description" style="width: 100%; height:200px;"></textarea></p>
<p><select name='catg' >
<option value='' selected >Select category</option>
</select>
<input type="submit" id='button' name="Submit" value="Submit" class="button"></form>
</body></html>
thanks
You've got two body tags. I suggest getting rid of one of them and seeing if that helps.
There's also a stray closing </font> tag in the middle of that code. Many people try to arrange their markup so that it's easy to read and to see the structure of the document. You might want to explore that practice.
Another possibility is that your "nicEdit" plugin is un-doing the ".focus()" call. Try taking that out and seeing if the focus works (as an experiment). If that's happening, then you can do your "focus()" call after the nicEdit code has finished:
bkLib.onDomLoaded(function() {
nicEditors.allTextAreas();
document.form.fbox.focus();
});
(That's an adaptation of the code in your existing <script> block.)
You have two body elements. That won't work.
Scripts run top-to-bottom, so you're firing the "onload" before the rest of the page has rendered. It's likely the element you are trying to focus is not there when the event fires.
There are a number of ways to fix this. jQuery has a handy method that waits until the DOM is ready.
A simple way is simply to run your script from the bottom of the page in a script block.
<script type="text/javascript">
document.form.fbox.focus()
</script>

Categories

Resources