Proper way to add onload function to body using jQuery - javascript

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
});

Related

How to load script tag after page has loaded?

I am trying to load an ad script right after the page has loaded. Usually, the ad script looks like this
<script id="someId" language="javascript">
someVar = thisValue;
somethingElse
</script>
Notice that it got already a <script> tag on it, removing it does not render the ad. So, it got to be in there no matter what, moreover, those things inside shouldn't be modified.
The problem with this is, I could not attempt to place it in a function.
I was trying to do this, to lunch the <script> tag on load
<script type="text/javascript">
function load() {
//this is were the add goes
<script id="someId" language="javascript">
someVar = thisValue;
somethingElse
</script>
}
</script>
Then lunch the function by means of
<script type="text/javascript">window.onLoad = load;</script>
So that is technically what I am trying to do, but I cant get this code executed. What would be the best, to run the '' tag ad after page load?
Easy way to handle your jQuery before or after page loads:
jQuery(function($){
// Use jQuery code here with $ formatting.
// Executes BEFORE page finishes loading.
});
jQuery(document).ready(function($){
// Use jQuery code here with $ formatting.
// Executes AFTER page finishes loading.
});
Then inside second section, which handles jQuery after page loads, use jQuery.getScript() to load your Javascript file:
$.getScript('/js/main.js');
If you would like new JS to fire off as soon as JS file loads, simple done like so:
$.getScript('/js/main.js', function() {
// Executes AFTER main.js file is loaded.
});
Click here for jsFiddle example.
A quick search for lazy loading found this
<script>
var resource = document.createElement('script');
resource.async = "true";
resource.src = "http://example.com/script.js";
var script = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(resource, script);
</script>
Well, there are 2 major mistakes:
window.onload = load; (not onLoad)
It doesn't make sense to write the <script> inside of the function declaration
<script>
function load() {
//this is were the add goes
someVar = thisValue;
somethingElse
}
window.onload = load;
</script>
Can't you write something like that?
If you can't, at least, try to move your <script> to the end of <body>.
Placing scripts at the bottom of the element improves the display speed, because script compilation slows down the display.
If you really need <script id="someId" language="javascript">,
just place it this way:
<script id="someId" language="javascript">
function load() {
//this is were the add goes
someVar = thisValue;
somethingElse
}
window.onload = load;
</script>
Try this way:
<script async src="url_to_ad"></script>
It may work. The boolean async attribute on script elements allows the external JavaScript file to run when it's available, without delaying page load first.

js function does not exist?

Using MVC...
<a onclick="confirmDeactivate(#mobileDevice.Id, '#mobileDevice.IsActive');" class="show-pointer"><i class="icon-trash"></i></a>
So Id, and boolean will be passed to confirmDeactivate...
<script type="text/javascript" language="javascript">
function confirmDeactivate(mobileDeviceId, mobileDeviceIsActive) {
var i =1;
}
</script>
It is telling me confirmDeactivate is undefined.
what am i doing wrong?
EDIT
inspect element:
You need to make sure that the script where you have your function is loaded before you try to call it. If it is an external file, Make sure you load that in your HEAD section/ Top of your razor view.
OR you can try an unobutrusive approach
I updated the markup a little bit, Added a css class name and some data attributes.
<a class="show-pointer clicky" data-deviceid="#mobileDevice.Id"
data-active="#mobileDevice.IsActive"><i class="icon-trash"></i></a>
and in your javscript, Bind a click event to your anchor tag and wrap it inside your document ready.
<script>
$(function(){
$("a.clicky").click(function(e){
e.preventDefault();
var _this=$(this);
var deviceId=_this.data("deviceid");
var isActive=_this.data("active");
alert(deviceId+", " +isActive);
//do something with the values now
});
});
</script>

$(document).ready can't replace js declared at bottom of the page, but I need to have the script at the top

I have JQuery based tab navigation that only works if it is placed after the html for the menu. It works if it's placed at the end too, but breaks when I put the same script in $(document).ready ath the top.
I thought that this (placed at the top of the page):
<script type="text/javascript">
$(document).ready(function(){
mouseovertabsmenu.init("mytabsmenu", "mysubmenuarea", true);
});
</script>
would be the same as this:
<script type="text/javascript">
mouseovertabsmenu.init("mytabsmenu", "mysubmenuarea", true);
</script>
</html>
Which is placed at the bottom of the page and works. How would I be able to put the function at the top or even include it from a separate file?
I had this problem and I had used this in the head after the jquery include link:
$(document).ready(myfunction());
This failed due to objects not being loaded. I should have wrapped my call in a function:
$(document).ready(function () {
myfunction();
});
This worked as expected only after the document was properly loaded.
The reason it is recommended to place the script at the end of the page , is so that the HTML elements are loaded onto the page before you try to access them..
No matter where you place the code it is better to wrap in DOM ready event which makes sure the complete HTML document is properly loaded before you try to access the elements in the page..
Maybe in your case
<script type="text/javascript">
mouseovertabsmenu.init("mytabsmenu", "mysubmenuarea", true);
</script>
seems to be working when not encased in DOM ready is the function is not accessible as it's scope is being blocked by DOM ready

jQuery not loading at all

I'm trying out jQuery for the first time, and I'm not sure how to make it work properly. I've included the following code near my opening <head> tag:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
Followed by the following jQuery code:
<script>
$('.darkmask > img').hover(function(){
$(this).parent().toggleClass('darkmask-hover');
})​
</script>
Unfortunately, this code doesn't work when I try it in a browser, or in JSFiddle. However, when I set JSFiddle's framework to load jQuery itself, rather than loading jQuery through my own code, the animation works properly.
Am I loading jQuery wrong? If so, what's the right way?
PRoblem is, your code in JSFiddle is executed on the loading on the page. In your code instead, the execution happens when the HTML elements are not yet loaded because it's in the HEAD, so the selectors like .darkmask actually refer to... nothing.
The solution is to use:
$(document).ready(
function()
{
... your code here
}
To ensure that it is executed when the page is loaded and ready, all the HTML elements are there and therefore JQuery selectors can operate on something.
Are there any HTML elements when the code is executed?
Try:
$(function () { // this function executes when the page loads
alert(x);
// put your code here
});
Wrap your entire code in the following:
$(document).ready(function() {
//ALL CODE GOES HERE
});
Wrap your code in:
$(function() {
.... Your code here ...
});
It will mean your code is executed after the DOM tree is loaded.
You do need to wrap your jQuery code within the ready function, like this:
$(document).ready(function(){
// put your code here.
});
Also make sure your script tags have type="text/javascript" as an attribute otherwise it won't get run as javascript.

call function to highlight code

Please see the the following http://valogiannis.com/recent/ .I have a webpage and when user click XHTML code a div with id result loads the contents of a webpage (in this case codes/advocasys.html). In fact what I wish to do is to highlight the html code. I have link the necessary css/js. I use the SyntaxHighlighter 3.0.83. This highlighter needs to call the SyntaxHighlighter.all() after the <pre> tag (more info here). If I have the html code in the same page which I want to highlight works nice, but I cannot make it to work, when the script loads the external page advocasys.html. I tried to put the
<script type="text/javascript">
SyntaxHighlighter.all()
</script>
in the bottom of the advocasys.html, but It didn't work. How can I make it work?
Thanks in advance.
The .all() call attaches an event handler to window.load which already happened, instead use .highlight(), like this:
SyntaxHighlighter.highlight();
You need to call SyntaxHiglighter in the callback function after the data is returned:
$('#myLink').click(function(){
$('#result').load('codes/advocasys.html', function() {
$('#result').show();
$('.scroll-pane').jScrollPane();
SyntaxHighlighter.highlight();
});
return false;
});

Categories