I'm trying to scroll the page 50px before body load. But it always waits for body load before running the code.
I'm not quite sure what's the reason, I seem to remember running as they are parsed.
I tried with both, jquery and plain javascript, this is my code:
$(document).scrollTop('50');
window.scrollBy(0,50);
How do I make it work before body load?
there is no body when you are calling the event so nothing would happen
one way around to this is that set the height of body so some constant number
and add onLoad event on the body tag
<script>
SomeFunction(){
//scrollNow
}
</Script>
<body onLoad="SomeFunction()" style="height:500px;"></body>
Found one working solution, maybe somebody will find cleaner one.
This can scroll the page even before the onload:
document.writeln(' ');
document.body.style.height = '5000px';
$(window).scrollTop(50);
Test script here.
1. Create css offset class and assign to the body
.offset{
margin-top:-500px;
}
So that body will be loaded with 500px offset from top
2. Then add following code to the body
<body class="offset" onLoad="window.scroll(0, 150)">
3. then using jquery, remove offset class when page is loaded
$(document).ready(function(){
$(".row").removeClass("offset");
});
This will work http://www.frameinn.com/thatisuday/about
Related
Background
I've created a simple workaround to get a fixed background to work on iPad and iPhone devices, i.e creating an empty div just after the body tag with position:fixed rather than background-attachment:fixed which these devices doesn't support. All variations on the body element I've tried, like pseudo ::before is not working on these devices. An empty div solves this.
Problem
My script below works perfectly on my main page ('Home'/'Start'). But I also have other pages like 'Contact' and such, sharing the same 'global' head tag where the script lies, where it doesn't work (the div simply doesn't show up). I would expect this to add a div after each body element, regardless of which page is loaded... Also, I'm using window.onload as I can't manually add the script after the body tag. Each subpage body tag has its own id but why would that matter? What am I missing?
window.onload = function FixedBg() {
var body = document.body;
var bgDiv = document.createElement('div');
bgDiv.className = "fixedBackground";
body.insertAdjacentElement('afterbegin', bgDiv);
}
I don't have access to manually add divs directly into the DOM which obviously would have been the approach otherwise, hence the JavaScript...
As was suggested in the comments above by #ProfessorAbronsius and #TheFool, using DOMContentLoaded and an event listener did the trick! Thank you
I have a need to add a class to certain pages - ones that contain an ID of #hero. For all other pages, the class must not be added.
Because I'm using asp.net with a few layered master pages, its not as simple as just adding a class directly to the html becuase the body tag sits a couple of pages above the aspx page.
I could locate the body tag, but so far I've tried to avoid that due to the added complexity, and instead tried to use jquery.
Here's the code:
$(document).ready(function () {
updateBodyClasses();
});
function updateBodyClasses() {
if($("#hero")) {
$("html, body").addClass("hero");
}
}
Nothing complicated, but here's the rub. By the time the class has been appended, the page has been rendered and the class doesn't seem to have any effect. However, if I test it by adding the class directly to the html, it works - so I know the CSS works and that its a timing issue.
I suppose I could add the code higher up the page - jquery is deferred, so I would need to know the equivalent javascript to try it out.
Would appreciate any thoughts on this potential solution, or perhaps and other ideas.
/* UPDATE */
For clarity, it seems to be the HTML related class that isn't being applied.
You can alter the DOM without waiting for it to be ready.
You need to:
load jQuery in a synchronous way(without defer or async).
Put #hero element i above the script.
Please consider this example:
.red {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hero">I don't care about DOM being ready</div>
<script>
var $el = $('#hero');
if ($el.length) {
$el.addClass('red');
}
</script>
You can use IIFE(Immidiately Invocked Function Expression):
like:
(function()
{
if($("#hero")) {
$("html, body").addClass("hero");
}
})();
just put your function in document ready like
$(function(){
if($("#hero")) {
$("html, body").addClass("hero");
}
});
No real solution provided.
Not reasitic to change the whole site infrastructure - from one that defers jquery to loading it synchronously.
The two other jquery answers are as per the current setup and don't work.
The only working solution was provided by Tushar, although it would still require selective loading of the script, which was not included in the answer.
In the end, I used a workaround, which bypassed the need for any javascript. Instead of selectively adding a class to html tag, I added the css permanently to the html tag, affecting all pages. I then added an inner div, which reverses it out. This means that any page can now manipulate its own functionality directly without having to add classes to the html tag.
I have a button which acts as a 'copy url' button. This works fine on none mobile devices, however I believe you can't have such a function on mobile devices as they rely on flash. On most mobile sites users must manually copy URLs.
So, I want to remove my 'copy url' button once a mobile device has been detected.
Before you grill me, yes I've read:
Hiding DIV if using mobile browser
I tried the solution mentioned in that thread, however it does not work. Any idea why? Here is my codepen:
http://codepen.io/rjtkoh/pen/dPxKeg
<head>
<script>
var mobile = (/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
$('.test').css('display', 'none');
</script>
</head>
<div class= "test">yo test me</div>
Much appreciated.
It doesn't look like you're doing anything with the mobile variable. But before you can get any further, you have to address the issue that is preventing your $('.test').css('display', 'none'); from hiding the div:
The DOM element you are referencing does not exist at the time the script is executed. The script should be executed after the DOM element is created, which can be accomplished a couple of ways:
Move the <script> tag to after the element in the HTML. This assumes that the link to jQuery is somewhere before the script, not after.
Use jQuery's document.ready() function to execute the JavaScript only after the DOM is ready. Since you're already using jQuery, this is usually the most convenient way to do it.
E.g.:
<script>
$(document).ready(function() {
var mobile = (/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
$('.test').css('display', 'none');
});
</script>
The reason you're seeing this is because the DOM isn't fully built, so when you're trying to access it using $('.test'), it can't get it. You have to wait until it is fully ready.
Wrap your Javascript code in the ready function provided by jQuery:
$(document).ready(function () {
// your code goes here
});
This code will only be executed once all the DOM has been loaded.
Have a look at the documentation.
A simple way to do this is just add class to the html element when match some situation.
And use a selector to hide the elements you want you hide only when the class exist
This allows you to hide element even the <body></body> haven't actully loaded.
Besides, it requires minimal DOM operation.
So it won't lag the page when there are too many elements needed to hide.
Just put the codes in the <head></head>
<script>
if (navigator.userAgent.search("Some thing") >= 0 ) {
/*the html element*/
var root = document.documentElement;
root.setAttribute( "class", "hide-for-compitibility" );
}
</script>
<style>
html.hide-for-compitibility .selectors{
display : none;
}
</style>
Does anyone look at his codepen? Hey guy,
you did not include Jquery while using it. Put this in your HTML section <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
you put your script in wrong section, move it to JS section.
the mobile variable you obtained should be used in an IF statement. Example,
if (mobile)
$('.test').css('display', 'none');
else
$('.test').html('This ELSE leg should be removed');
Finally, getting the opinion of other answers that you should wrap your code inside a $(document).ready() function.
Here is an example and it do work. http://codepen.io/anon/pen/QweBgq
Another way that does not use Javascript is that you use CSS. Try below code in CSS section.
.test {
display: none;
}
#media (min-width: 768px) {
.test{
width: 200px;
height: 50px;
background: red;
display: block;
}
}
So I have some javascript for a website but at the moment the only way I can get it to work is if it is mixed in with the HTML. I've read this is bad practice, but I can't figure out how to get it to work as a script in the head section. Can anyone help me out? I have read tonnes of similar questions on here but can't get it to work.
Thank you,
Alex
Here's the code I have:
<li>About</li>
I'm then fading it out again by adding:
and having a div that spans the width and height of the page so the user can click anywhere, not sure if this is a good way and is alright to use.
Thanks
I think you just forget to use the document ready.
The code you need:
<head>
<script type="text/javascript">
$(document).ready(function(){
$('.about_button').click(function(){ $('.about_background, .about_close').fadeIn('fast'); });
$('.about_close').click(function(){ $('.about_background').fadeOut('fast'); });
});
</script>
</head>
In your html you can place the elements:
<li>About</li>
and then at the bottom of the body put a reference to a js file (it should be at the bottom of the file rather than in the head so that the html loads first and the elements are ready when you use js to bind event handlers to them)
<script src="<file path>"></script>
In an external js file you can bind the event handler to them:
$(".about_button").click(function(){
$('.about_background, .about_close').fadeIn('fast')
}
$(".about_close").click(function(){
$('.about_background').fadeOut('fast')
}
Use jquery selectors to target your HTML elements and put listeners on them:
$('.about_button').on('click', function() {
$('.about_background, .about_close').fadeIn('fast')
})
$('.about_button') is the selector you use to target the element.
on('click' sets an onclick listener on the targeted element
function() { ... } is the callback function that'll get called when the listener gets triggered
Use
<script src="path/to/file.js"></script>
In HTML 5 you dont need to specify the type, else you need to specify type="text/javascript"
I need to put a dynamic content on a div using javascript script. This div is on the top of the page so it will load first before other things below it. And there are really lot's of things down there. So, when I put the script on the ready() or onload, the div will be empty for 2 -3 seconds while other things are displayed. So, I tried putting the onload or ready() to this div.
//example div, which is on the header part of the page
<div id="cont1">
something goes here
</div>
//... and there are a lot of other things going down here.
I tried putting the onload="alert('test')" on the div tag
<div id="cont1" onload="alert('test')">
and also the jquery method
<script>
$("cont1").ready(function(){
alert("test");
});
</script>
Both methods don't work, as the alert is triggered only after the whole page is displayed.
but if I put the alert("test"); script immediately after closing the above div, it works fine (as the other things on the page is not displayed yet when the alert is showing).
<div id="cont1">
something goes here
</div>
<script>
alert("test");
</script>
But this method is kind of a bad design isn't it? So, any other way to achieve this?
If you want a javascript action to fire after a specific DOM element has loaded, simply place it immediately after the element, as you noted:
<div id="cont1">
something goes here
</div>
<script>
alert("test");
</script>
Some may disagree, but this is not bad design. As long at whatever occurs in this script pertains only to elements which occur prior to it in the HTML document, everything should be kosher. The DOM is loaded linearly in the order it appears in the document, so there is no case in which the script coming after #cont1 would occur prior to #cont1. If the script is lengthy, you could put it in a function in a header include then call the function there instead.
onload and the meta-event of "ready" apply the the entire DOM document, not just any DOM node, which is what you are attempting here.
I would stick with jQuery's $(document).ready(...) for code that requires the DOM to be present.
onload is unfortunately on the window only.
However, I have written a jQuery plugin called waitForImages that will fire a callback when images have loaded inside any container.
This is a bit half way but you can have a img of a single pixel same color as the background at the end of the div and have an onload on the img.