I've got a page I'm coding, and it's supposed to run this Javascript on every page load. The problem is, it seems to load completely randomly. Sometimes it runs, sometimes it just doesn't. Every reload seems totally random on whether it will work or not. This is very frustrating as I can't imagine it's an issue with the code at this point.
function randombg() {
var random = Math.floor(Math.random() * 6) + 0;
var bigSize = ["url('http://lh4.googleusercontent.com/-dsFg9OnYo5Q/T0hK7b0-xoI/AAAAAAAABL4/9_CPzXBCMfw/s800/animated%2520blue%2520stars.gif')",
"url('https://background-tiles.com/overview/blue/patterns/large/1026.gif')",
"url('https://78.media.tumblr.com/395d407e0762d7041cbe0197e3ea288c/tumblr_o3fxwiIAq61v8fqfeo1_540.gif')",
"url('http://backgroundcheckall.com/wp-content/uploads/2017/12/seamless-repeating-background-gif-12.gif')",
"url('https://other00.deviantart.net/b3aa/o/2009/312/0/8/143009517_95116_animated_starfield_tile.gif')",
"url('http://backgroundcheckall.com/wp-content/uploads/2017/12/seamless-repeating-background-gif-10.gif')"
];
document.getElementById("random").style.backgroundImage = bigSize[random];
alert("Success");
}
window.onload = randombg;
window.onresize = randombg;
#random {
width: 100%;
height: 450px;
border: 1px solid black;
background-image: url('http://placehold.it/300&text=banner1');
background-position: center center;
background-size: cover;
background-repeat: no-repeat;
}
<body onload="randombg">
<div id="random"></div>
<body>
This is taken from this pen, which works flawlessly. So I'm very confused as to why it's not working consistently for me.
I'm running Chrome (67.0.3396.99) in Windows 10 (1803), and this code is being run in the extension Super Evil New Tab, which has a section for HTML, CSS, and JS.
Thank you for any feedback or advice.
EDIT: I forgot to mention that the extension seems to just stick the HTML into a body.
The simplest, non-library-dependent way to fix inconsistent JavaScript initialization execution is to change <body onload="randombg"> to just <body> and insert your JavaScript before your script tag like so:
<script src="path/to/your/js/file/here.js"></script>
<body>
<div id="random"></div>
</body>
And then in your JavaScript file, instead of using window.onload = ..., do:
// This method of attaching a function to a DOM event allows for more flexibility down the line.
window.addEventListener('load', randombg);
window.addEventListener('resize', randombg);
If you use this addEventListener way, if you choose to do more than just randombg on load and resize events, you could just do
window.addEventListener('load', () => {
randombg();
// more code to perform on load here...
});
window.addEventListener('resize', () => {
randombg();
// more code to perform on window resize here...
});
Related
I have some <img> tags and some <div> tags with 'background: url('example.jpg');
And I want to wait until these images are downloaded and not execute any following javascript code ultil these images are downloaded and loaded. So only after I can call a function to deactivate my website loader and keep adding the other scripts for animating and stuff...
PS: I don't want to wait ultil all images are loaded cause that will take too long, i just want some images (like the first background) to be loaded before I deactivate my website loader...
You could load it into memory first then apply it to the element
var img = new Image();
img.onload = function() {
console.log('image loaded');
document.querySelector('div.bg').style.backgroundImage = `url(${img.src})`
}
img.src = "https://picsum.photos/200/300?" + new Date().getTime();
div.bg {
height: 500px;
width: 600px;
background: #000;
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
<div class='bg'></div>
Javascript-beginner here, so I don't know if there are any existing functions or anything that might take care of this for you.
My search-results came empty-handed to your specific question, so this is what I would do if I was sure there is nothing out there:
periodically check whether a number of images already have a size.
Should be easy enough to build a dynamic list, or to specify a few specific images you want to load, I guess.
I've got a minor problem I'm trying to resolve on my website. I have it currently so that a loading screen div appears above the page when the user visits and then fades away after a set time/the page is loaded, whichever comes latest. I want this div only to appear on first visit and would prefer to avoid cookies or anything server side. From what I understand I want to utilize session storage or referrer but have not had success with implementing that. Also, subsequent pages have a less prominent and faster loading screen that will have to go away only when each individual page has been visited once during the session. The applicable code is:
css:
.js div#preloader {
position: fixed;
left: 0;
top: 0;
z-index: 1000;
width: 100%;
height: 100%;
overflow: visible;
background-color: #202020;}
#preloader {
z-index: 1000; }
js:
jQuery(document).ready(function ($) {
$(window).load(function () {
setTimeout(function(){
$('#preloader').fadeOut(1500, function () {
});
},5000);
});
});
So it's likely obvious that I'm not well informed; I'm teaching myself as I go and needless to say I have a lot to learn about javascript. If I've done something horribly wrong here, which is entirely plausible, or a working demo is required, please let me know.
Thanks!
You can probably accomplish what you want using the sessionStorage object. In that object, you can track which pages have been visited in the current session.
The issue you can run into with JavaScript (and the reason I said it may not be the best approach) is that, when using a library, there is always a finite amount of time that passes while the library is loaded, parsed, and executed. This makes your "only appear on the first visit" requirement somewhat difficult to accomplish in JavaScript. If you show it by default and hide it with library code, it will show briefly each time you go to the page. If you hide it by default and show it with library code, it will be briefly hidden the first time you go to the page.
One way to handle this is to use embedded JavaScript that is executed immediately after the DOM for the preloader is defined. The downside to this is that you have to know how to write cross-browser JavaScript without assistance from a library like jQuery. In your case, the JavaScript required to simply hide the preloader is simple enough that it shouldn't have any cross-browser issues.
I created a simple page that demonstrates the technique. The source for this page is:
<html>
<head>
<style>
#preloader {
position: fixed;
left: 0;
top: 0;
z-index: 1000;
width: 100%;
height: 100%;
overflow: visible;
color: white;
background-color: #202020;
}
</style>
</head>
<body>
<div id="preloader">Preloader</div>
<script>
if (sessionStorage[location.href]) {
document.getElementById('preloader').style.display = 'none';
}
sessionStorage[location.href] = true;
</script>
<p>This is the text of the body</p>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(function () {
setTimeout(function(){
$('#preloader').fadeOut(1500);
}, 5000);
});
</script>
</body>
</html>
I also created a fiddle for it: http://jsfiddle.net/cdvhvwmm/
my case is a little different than the previous ones that have been posted so far.
I want my iframe to resize using a function with javascript.
The source for my iframe so far looks like this
<iframe id='bframe' onload='base=history.length;gothere(history.length);' name='bframe' src='http://source.com' style='border: 0pt none ; left: -794px; top: -166px; position: absolute; width: 1600px; height: 799px;' scrolling='no'></iframe></div>
The reason for the "onload" stuff is because I want the iframe to resize when an action within the iframe has been done! The only thing I need now is a function in javascript that allows me to change the width and height as well as top and left coordinates of the iframe.
That would be all, help is really appreciated!!!
Thanks
EDIT:
--
THANKS for the response but i seemingly can't get it to work:
Hey, thanks for your response.
I put my code like this into the part of my page
function resizeme() {
document.getElementById('bframe').onload = function() {
this.style.width = '1230px';
this.style.height = '1230px';
base = history.length;
gothere(history.length);
}
}
and I replaced the part in my code where it redirects to another page after the iframe content has changed to "resizeme()" (the redirection worked so the code must be correct)
However, nothing really changed - What is wrong?
Same as all (block-level) elements:
element.style.width = '123px';
element.style.height = '123px';
In this case:
<iframe id='bframe' onload="this.style.width='123px';this.style.height='123px';base=history.length;gothere(history.length);" name='bframe' src='http://source.com' style='border: 0pt none ; left: -794px; top: -166px; position: absolute; width: 1600px; height: 799px;' scrolling='no'></iframe></div>
You should really put it in a function, tho:
document.getElementById('bframe').onload = function() {
this.style.width = '123px';
this.style.height = '123px';
base = history.length;
gothere(history.length);
}
In your specific case,
function resizeme() {
document.getElementById('bframe').style.width = '1230px';
document.getElementById('bframe').style.height = '1230px';
}
document.getElementById('bframe').onload = function() {
resizeme();
base = history.length;
gothere(history.length);
}
At least that's what I think you're trying to do. It defines a resizeme function that you can call whenever you like, and also gives the iframe an onload function to call resizeme and do other stuff (base and gothere).
http://jsfiddle.net/TmUfE/
Here we go! The source is a bit messy I didn't code it and I'm not an expert in this. However it should do this:
Whenever a link is pressed (more like a submit button in the iframe), it should redirect the whole page to something else. That has been the original source and it worked for my "special" site which I didn't put in the jsfiddle so the source itself is working for that matter!
I wanted to modify it so that when the submit within the iframed is clicked, it resizes and repositions the iframe (to crop another part of the second page and also have a larger iframe shown the content of it).
I found that this part
<div style='overflow: hidden; margin-top:-5px; width: 403px; height: 313px; position: relative;' id='odiv'>
was also doing its part when it comes to resizing it (thats why it didnt work in the first place).
So the first task would be: To resize the iframe in the iframes source with the width and height and such + the part I just entered here as well (dont know how to figure that out
and how to resize them via code).
I would also be paying as some sort of "thank you" / donate to someone helpful because I really cannot get it done myself no matter how hard I try.
I am working on an app for desktop/mobile. The jQuery $(document).ready(); is definitely firing, which is why the app works. However, in the Chrome mobile browser, one particular function (to add some dynamic CSS to one element to place it correctly) is not firing correctly, and thus not updating the CSS when the page loads. The function fires normally and updates the CSS in the desktop browser. Here is the code:
$(document).ready(function() {
function placeBook() {
var h = $('#header').css('height');
$('#button').css('height', h);
$('#button').css('line-height', h);
}
placeBook();
$(window).resize(function() {
placeBook();
});
});
The function placeBook() is not updating the CSS of the #button div on the first load of the page. However, the function fires normally on resize of the window, as specified in the code. It only fails on the mobile browser at the initial load of the page. See these SS's:
First load in desktop (FF responsive design view):
First load in mobile (Chrome):
As you can see, the idea is that the book icon is to be centered vertically in the header. Of course, any help is appreciated.
Here is the HTML/CSS:
<div id='header'>
<div id='button'></div>
</div>
#header {
position: fixed;
top: 0;
width: 100%;
font-size: 120%;
text-align: center;
}
#button {
position: absolute;
top: 0;
left: 0;
padding: 0 1%;
}
Had a similar problem in Chrome: css is not being applied to dom, but when updated in console or styles are modified starts applying.
The problem was in sending incorrect mime type in headers of css files. This is chrome-specific peculiarity, because FF was more forgiving. Sending "text/css" fixed problem.
Hope it helps.
As per this answer:
window.load doesn't fire always on chrome?
It seems that it isn't safe to use $(window).load(); on chrome, especially when it comes to DOM modifications. Instead use $(document).ready();! I've created a simple fiddle to confirm that load isn't always firing in chrome: http://jsfiddle.net/KvD6G/
Furthermore, instead of fixing this with javascript try doing it with css by applying the following styles:
#button {
...
display:inline-block;
vertical-align:middle;
...
}
I think you have to place your placebook() function in the global scope, outside of doc ready handler:
function placeBook() {
var h = $('#header').css('height');
$('#button').css({
'height': h,
'line-height': h
});
}
$(window).load(function() {
placeBook();
$(window).resize(function() {
placeBook();
}).resize(); //<----invokes the resize function immediately
});
Although you have not mentioned your doc ready handler:
function placeBook() {
var h = $('#header').css('height');
$('#button').css({
'height': h,
'line-height': h
});
}
$(function(){ //<------------------doc ready handler
$(window).load(function() {
placeBook();
$(window).resize(function() {
placeBook();
}).resize(); //<----invokes the resize function immediately
});
});
I'm trying to detect when the onresize event ends in a browser. If I use the onresize event, in Firefox it seems to be fired only once, after the resize event ends, which is exactly what I want. But if I try in IE, the onresize event gets fired many times during the resize.
I also try the onresizeend event, advertised in MSDN. But it does not seem to get fired at all, neither in Firefox, nor in IE. I use the following code:
<html>
<head>
<script>
<!--
function doLog(message)
{
document.getElementById("log").innerHTML += "<br/>" + message;
}
function doResize()
{
doLog("plain resize");
}
function doResizeEnd()
{
doLog("resize end");
}
-->
</script>
<style>
<!--
#log {
width: 400px;
height: 600px;
overflow: auto;
border: 1px solid black;
}
-->
</style>
</head>
<body onresize="doResize();" onresizeend="doResizeEnd();">
<div id="log"/>
</body>
</html>
Any ideas why this does not work? Maybe the onresizeend event is not supported? In this case, how can I detect when the resize event has ended?
From MSDN onresizeend()
Only content editable objects can be
included in a control selection. You
can make objects content editable by
setting the contentEditable property
to true or by placing the parent
document in design mode.
That explains why it's not firing for you. I suspect you don't want to enable contentEditable, so why not set a timer.
var resizeTimer = 0;
function doResize()
{
if (resizeTimer)
clearTimeout(resizeTimer);
resizeTimer = setTimeout(doResizeEnd, 500);
}
It's not perfect but hopefully will be good enough.