Image rotate background js jumps to top of the page - javascript

I have a problem with javascript that I don't know how to solve. First of all I am a total newb in this. I found a code that loads random images in div element and tweaked it a little bit (original code loaded images in order - I inserted a type of algorithm for randomness (pretty clumsy but it somehow works and rarely repeats the same image one after another).
Now the code works just fine, but when I scroll for e.g. to the bottom of my page the instant moment that script loads a new image into div element browser jumps to the top of the page.
How to stop this from happening? Please help me with a 'child language'(because as I told, I'm a total newb in js).
Thank you all in advance for your time!
<script src="js_vrt/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function() {
var images = ['img_vrt/pozadine/1p.jpg', 'img_vrt/pozadine/2p.jpg', 'img_vrt/pozadine/3p.jpg', 'img_vrt/pozadine/4p.jpg'];
var image = $('#pozad');
var i = Math.floor((Math.random() * images.length) + 0);
var ist;
//Initial Background image setup
image.css('background-image', 'url(' + images[i++] + ')');
//Change image at regular intervals
setInterval(function() {
image.fadeOut(1500, function() {
image.css('background-image', 'url(' + images[i++] + ')');
image.fadeIn(1500);
});
if (i == images.length)
i = Math.floor((Math.random() * (images.length - 1)) + 0);
else i = Math.floor((Math.random() * (images.length)) + 0);
}, 5000);
});
</script>

Solution I figured out:
Problem is not in the js code. It is in HTML structure.
If someone has the same problem where screen jumps to top of the page while loading images do the following:
The div element that has the changing background MUST be contained in another wrapping div (which has the same height).
<div id="wrap_element">
<div id="div_that_loads_the_images"></div>
</div>

Related

Position image randomly after each onclick event (image must be in div tag)

So I am very new (as I am sure my code shows :P) and I must create code that contains an image in a div tag. It must be this way. Once the document is opened the image(div) is to be displayed at a random position. Each time the image(div) is clicked, the image alone moves to another random position. It does not replicate itself. Just moves. I have had other "better" attempts but with all my editing and changing all I get is the image in the top left corner.
I tried numerous things that all failed to work. Obviously failed because the code was terrible.
I have tried a variation of onclick events etc...I know many errors are visible. This is not one of those instances where I believe the logic is sound and it should work. This is a "what am I at" instance
<script>
function fpos () {
var img = document.getElementById('myImage') //is this needed at all?
var x = Math.floor(Math.random()*600);
var y = Math.floor(Math.random()*600);
var z = Math.floor(Math.random()*600);
}
function rmove() {
img.style.top = x + 'px';
img.style.left = y + 'px';
}
</script>
</head>
<body onload="fpos">
<div style = position:absolute; onclick="rmove" >
<img id="myImage" src='images/iasip.jpeg'> </img>
</div>
</body>
So, first, don't take this the wrong way my man but you gotta post some code to show us what you're working with. Makes all the difference for troubleshooting.
That said, you're gonna need to do with with JS. First target the image element. Can use querySelector to hit either the class or id or just getElementById.
Then add an event listener to render it at a random coordinate. Like this.
<div id="imageContainer">
<img src="your-image-source" alt="your-image-description">
</div>
<script>
// get the image container element
var imageContainer = document.getElementById("imageContainer");
// set the initial random position for the image container
imageContainer.style.left = Math.floor(Math.random() * window.innerWidth) + "px";
imageContainer.style.top = Math.floor(Math.random() * window.innerHeight) + "px";
// when the image container is clicked, set a new random position
imageContainer.addEventListener("click", function() {
imageContainer.style.left = Math.floor(Math.random() * window.innerWidth) + "px";
imageContainer.style.top = Math.floor(Math.random() * window.innerHeight) + "px";
});
</script>
Can either do that inline like in the example or add it to your script file.
Here is a working example I just threw together.
Basically you need to create a function that moves the image each time by calculating a random number for the height and width and then multiplying by the size of the window so that number can span the full width/length of the screen.
Then you can add 'px' to the end of the calculation to use pixels as the unit and set that to the left and top properties of the image to move it that far from the left and top of the screen using absolute position (coordinates).
window.onload = function() {
move()
}
function move() {
let img = document.getElementById('logo')
img.style.left = Math.floor(Math.random() * window.innerWidth) + "px"
img.style.top = Math.floor(Math.random() * window.innerHeight) + "px"
}
#logo {
height: 100px;
position: absolute;
}
<div>
<img onclick='move()' id='logo' src='https://upload.wikimedia.org/wikipedia/commons/thumb/2/24/LEGO_logo.svg/2048px-LEGO_logo.svg.png' />
</div>
Don't worry, try to isolate some code so we can review it.
Once the document is opened the image(div) is to be displayed at a
random position.
By inspecting an element's properties with Right Click > Inspect > Property you'll find all javascript properties that you have access to once you select the element with a selector (document.querySelector for example)
Try something with that, i think that the easiest way is to use
element.style.transform = "translate(x,y)"
like x.style.transform = "translate(10px, 20px)";

How to load an onScroll background image before user scrolls to them?

I'm changing background of a div when the user scrolls to the end of that div. Since its a fixed background, I am not using HTML <img> tag, instead I am using the CSS background-image:. With the following JavaScript function, it successfully changes the background when i need it, and reverts back when user scrolls back to top.
function transimg(divid,imgurl1,imgurl2) {
$(window).scroll(function(){
var st = $(this).scrollTop();
var dist = $(divid).offset().top - 50;
if(st > dist) {
$(divid).css("background-image", "url(" + imgurl1 +")");
}
else{
$(divid).css("background-image", "url(" + imgurl2 +")");
}
});
}
My Question is:
Obviously this loads the image when user scrolls to that offset. Which makes it slow when i host the site and a user has slow connection. So i need the 2nd image to be loaded when the page starts loading. Kind of the opposite of Lazy Load. How can i achieve this ?
I really don't want to use any plugins.
Any help is appreciated, thanks in advance !
You can load them in the before body is load. (Add the script at the end of your body).
Explanation: When you create an Image and set is the src property the image file download to your browser.
var images = ['img1', 'img2'];
for (var i = 0; i < images.length; i++) {
var img = new Image();
img.src = images[i];
}
you could add 2 background-images to the divid and so they are both loaded at page refresh and then with your JQ toggle between background-images depending on scroll.
see snippet below. let me know if it helps ( i check in Network and both images are loaded when page refresh )
$(window).scroll(function(){
var st = $(this).scrollTop();
var dist = $("#container").offset().top - 50;
if(st > dist) {
$("#container").css("background-image", "url(" + "http://i.imgur.com/AsqlqnG.jpg" +")");
}
else{
$("#container").css("background-image", "url(" + "http://i.imgur.com/I8170KA.jpg" +")");
}
});
#container {
background-image : url("http://i.imgur.com/I8170KA.jpg"),url("http://i.imgur.com/AsqlqnG.jpg");
background-size:contain;
background-repeat:no-repeat;
height:800px;
width:100%;
margin-top:50px;
position:relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id ="container">
</div>

Scrolling content in a div when it's passed

Trying to accomplish something like on this website:
http://www.strangelove.nl/cases/kpmg-meijburg
The part where the responsive design is showcased, the image inside the devices start to scroll when a visitor scrolls past that point. I've tried to replicate it and I see a .js in the footer which is probably contributing. For now I have the css and html working on my test page.
Any help is gladly appreciated.
Strangelove is using their own Kubrick-js, which is available here: Kubrick-js
If you just want to have the 'images scrolling inside of frame while scrolling by'-effect, you can do it like this:
$(window).scroll(function() {
var animStart = 0, // the point where the animation starts
animEnd = 500, // the point, where the animation ends
scrollStartPos = 0, // the position your inside scrolling element starts
scrollEndPos = -300, // the position your inside scrolling element should end
winPosY = window.pageYOffset, // the scroll distance from top of document
scrollElement = $('.picture'); // the element to scroll
if(winPosY > animStart && winPosY < animEnd) {
// how far through the animation are we?
var howFar = (winPosY - animStart) / (animEnd - animStart),
scrollPos = Math.round(scrollStartPos + howFar * (scrollEndPos - scrollStartPos));
scrollElement.css('top', scrollPos + 'px');
$('.show-stats').html('How far: ' + howFar + '<br>scroll Position: ' + scrollPos);
}
});
Here is a fiddle for it: Fiddle
hope that helps.

adding fade to change background with javascript

I have the following code for changing a divs background image with jquery, i need help to add a fade to the code so the image change with some effect
this is the code
jQuery(window).load(function(){
var images = ['blured/1.jpg','blured/2.jpg'];
var i = 0;
var timeoutVar;
function changeBackground() {
clearTimeout(timeoutVar); // just to be sure it will run only once at a time
jQuery('#maincont').css('background-image', function() {
if (i >= images.length) {
i=0;
}
return 'url(' + images[i++] + ')';
});
// call the setTimeout every time to repeat the function
timeoutVar = setTimeout(changeBackground, 6000);
}
// Call it on the first time and it will repeat
changeBackground();
});
Any help will be great!
i need to just change the background image, without fading the inside divs, this is the html
<div class="maincont" id="maincont">
<div class="containersrch">
<h1 class="lagro">some title</h1>
<div class="joinus">
<span>JOIN</span>
</div>
</div>
Maybe this is what you want?
$(function(){
var imgId = $('#maincont'), imgCount = 1, imgLast = 2;
setInterval(function(){
imgId.fadeOut('slow', function(){
if(++imgCount > imgLast)imgCount = 1;
imgId.css('background', "url('blured/"+imgCount+".jpg')");
imgId.fadeIn('slow');
});
}, 6000);
});
Now you can have multiple images, just change imgLast to the last number and make sure they have the correct URLs in your blured folder. Of course, the code above assumes you are using .jpg. I actually recommend the lossless compression of .png, but it won't matter if it's the image was taken as a .jpg.

How to slide images in from the side using JavaScript?

I have a script that displays images sort of like a carousel. The images are placed in LIs and the left positioning is changed based on the width of each slide (all the same). Currently, the old slide just disappears then the new one appears.
I would like to make it so they slide in from the side and was wondering if someone could give me a basic example of how to do this using plain JavaScript (no jQuery!).
For example, I'm using the following code to update the left positioning of the containing UL. How can I make it so it will slide the selected image to the left or to the right (depending upon whether the next or previous button is clicked)
containingUL.style.left = '-' + (slideNumber * slideWidth) + 'px';
Here's a basic element slide function. You can play with the values of steps and timer to get the animation speed and smoothness just right.
function slideTo(el, left) {
var steps = 25;
var timer = 25;
var elLeft = parseInt(el.style.left) || 0;
var diff = left - elLeft;
var stepSize = diff / steps;
console.log(stepSize, ", ", steps);
function step() {
elLeft += stepSize;
el.style.left = elLeft + "px";
if (--steps) {
setTimeout(step, timer);
}
}
step();
}
So you could go:
slideTo(containingUL, -slideNumber * slideWidth);
Edit: Forgot to link to the JSFiddle
Edit: To slide to the left, provide a left value less than the current style.left. To slide to the right, provide a value greater than the current style.left. For you it shouldn't matter much. You should be able to plug it into your existing code. I'm guessing your current code either increments or decrements slideNumber and then sets style.left according to the slideNumber. Something like this should work:
if (nextButtonClicked) slideNumber++;
else slideNumber--;
slideTo(containingUL, -slideNumber * slideWidth);
I updated the JSFiddle with a working example of a sliding "gallery", including prev and next buttons. http://jsfiddle.net/gilly3/EuzAK/2/
Simple, non jQuery:
http://sandbox.scriptiny.com/contentslider/slider.html
http://www.webmonkey.com/2010/02/make_a_javascript_slideshow/
http://javascript.internet.com/miscellaneous/basic-slideshow.html

Categories

Resources