Animate background image javascript not working - javascript

I want to achieve a background animate image, that moves from right to left, but the image won´t animate, could you help me verify my code?
<body>
<div id="background-container"></div>
<script> type="text/javascipt">
function animateBackground(elem, speed) {
var x = 0 ;
var y = -50;
elem.style.backgroundPosition = x + 'px' + ' ' + y + 'px';
var timer = setInterval (function(speed) {
elem.style.backgroundPosition = x + 'px' + ' ' + y + 'px';
x--;
if (x == -600) {
clearInterval(timer);
}
},speed)
}
document.addEventListener("DOMContentLoaded", animateBackground(document.getElementById('background-container'), 15), false);
</script>
</body>

Your code is quite ugly but actually it looks fine. What is definitely wrong is how you are adding the event handler. Instead of adding a handler function, you call your handler function inline, so it actually doesn't add any listener. You should pass the function itself, for example like this, using an anonymous function inline.
document.addEventListener("DOMContentLoaded", function() { animateBackground(document.getElementById('background-container'), 15); }, false);

You could have provided a jsfiddle link, which would have made it easy. By the way here is the working jsfiddle, https://jsfiddle.net/pmankar/4o88z0tt/
I added a css background to the div tag using
div{
background-image: url("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png");
height: 100px;
width: 600px;
border: 2px solid green;
}
Rest assured, I didn't do any changes to your js code or the html code. It worked fine for me.

Related

Change background url of div via HTML tag

I have a div (CSS - height: 250px, width: 70%) and I have set a background via CSS. I want to change the background onhover.
That's simple, I know. But I want to get sources of backgrounds from the HTML tag.
Ex.:
<div class="somediv" data-imgbefore="img1.png" data-imgafter="img2.png"></div>
Can anyone help me please?
If you're not using jQuery you can achieve the desired effect using basic Event Listeners. https://jsfiddle.net/gnu9utos/3/
// first get the element that we'll be interacting with
var element = document.querySelector('.somediv');
// assuming we managed to successfully get the element from the document
if(element) {
var before = element.getAttribute('data-imgbefore');
var after = element.getAttribute('data-imgafter');
if(before && after) {
element.style.background = 'url(' + before + ')'; // set the initital state
element.addEventListener('mouseover', function(event) {
element.style.background = 'url(' + after + ')';
});
element.addEventListener('mouseout', function(event) {
element.style.background = 'url(' + before + ')';
});
}
}
You might want to add a check for mouseleave to revert the image back to it's original state and add a little bit of css.
I hope this was helpful.
you can do this with this simple JQ
maybe it's not the best solution but it works.i added background-color so you can see the change. but you can remove that and leave only background-image
see here
jsfiddle
made 2 variables and assigned them to each image ( before and after img ) to each div with class .somediv
add an initial background-image to the div
then at hover, the background-image of the div changes between imgbefore and imgafter
jq :
$(".somediv").each(function(){
var imgbef = $(this).data("imgbefore"),
imgaft = $(this).data("imgafter")
$(this).css({'background-image': 'url(' + imgbef + ')','background-color':'red'});
$(this).hover(function(){
$(this).css({'background-image': 'url(' + imgaft + ') ','background-color':'blue'});
}, function(){
$(this).css({'background-image': 'url(' + imgbef + ')','background-color':'red'});
});
});
HTML :
<div class="somediv" data-imgbefore="img1.png" data-imgafter="img2.png"></div>
CSS :
.somediv {
height:250px;
width:70%;
}
let me know if it helps
You can easily achieve that with javascript. You can also add an onmouseleave function, but this time, passing this.dataset.imgbefore as second argument.
changebg = function(el, i) {
var t = "url("+i+")";
el.style.backgroundImage = t;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="somediv" id="mydiv" data-imgbefore="http://lorempixel.com/400/200/sports" data-imgafter="http://lorempixel.com/400/200/animals" onmouseover="changebg(this, this.dataset.imgafter)">Lorem</div>
</body>
</html>
You can add all the div that you like and change only the data-imgbefore and data-imgafter !!!
$(document).ready(function(){
$('.somediv').each(function( index, value ) {
var img = $(this).attr('data-imgbefore');
$('.somediv').css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
});
//$('.somedive').css({'background-image':'url("http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png")', 'background-size':'200px 200px'});
$('.somediv').hover(
function () {
var img = $(this).attr('data-imgafter');
$(this).css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
},
function () {
var img = $(this).attr('data-imgbefore');
$(this).css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
}
);
});
.somediv {width:200px;height:200px;border:1px solid #F2F2F2;border-radius:4px;display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="somediv" data-imgbefore="http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png" data-imgafter="http://www.filastrocche.it/contenuti/wp-content/uploads/2001/04/pippogoofy_352.jpg"></div>
<div class="somediv" data-imgbefore="http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png" data-imgafter="http://www.filastrocche.it/contenuti/wp-content/uploads/2001/04/pippogoofy_352.jpg"></div>
Cheers!!!
Not sure if I understand what you are trying to accomplish. Why don't you abandon the HTML tag requirement and just try css :hover?
#somediv {
background: url(...);
}
#somediv:hover {
background: url(...); /* different url */
}
http://www.w3schools.com/cssref/css3_pr_background.asp

How to increment jQuery variable?

I'm trying to browse through a picture gallery with jquery, so I have a button which is supposed to increment a variable by 1 and then use that to load the next picture.
Using the top answer on this SO question, I thought this would be the solution:
<div id="pic"></div>
<div id="browse-right">NEXT</div>
<%= image_tag("/1.JPG", id:"1") %>
<%= image_tag("/2.JPG", id:"2") %>
<%= image_tag("/3.JPG", id:"3") %>
$("#1").click(function() {
var x = 1;
$("#pic").html('<img src="/' + x + '.JPG" />');
});
$("#2").click(function() {
var x = 2;
$("#pic").html('<img src="/' + x + '.JPG" />');
});
$("#3").click(function() {
var x = 3;
$("#pic").html('<img src="/' + x + '.JPG" />');
});
//...
$("#browse-right").click(function() {
x = x + 1;
$("#pic").html('<img src="/' + x + '.JPG" />');
});
But it just reloads the same picture, which means var x doesn't change. Anyone know the proper syntax?
UPDATE: Okay, I think I've figured out the problem. x is set when a picture is clicked on, and apparently it isn't persisting after the function is complete. I didn't include that part in the original code because I thought it would make the whole thing more complicated to read.....lesson learned. How can I get x to persist after the function it is set in?
How can I get x to persist after the function it is set in?
Try defining x outside of and before click handler
var x = 1;
$("body").on("click", function() {
x = x + 1;
$(this).html(x)
})
body {
width: 300px;
height: 300px;
border: 1px solid purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
click
Your code looks ok. and here's a working version https://jsfiddle.net/a50nz178/1/
A couple of things you could check:
check that the image is actually there /1.JPGas well
check that images are not all named as jpg all lower case?
If I had to guess, looking at your previous You've updated. Turns out I was right. Your x was out of scope. correct code, I'd bet your problem is scope. Scope Tutorial
I'm willing to bet, somewhere else in your code your using something like for(x in ; ... Which is reassigning x. If that's not the case, I'd still bet on either scope, or the image is src isn't correct. You should use your developer console to check if a bad image source is being pulled. Your using / at the begining of your img src which will go back to base path. If you images are in an images folder you need to include the proper directory path.
You could easily shorten the scope of this by attaching your increment variable to your element object like so:
$("#browse-right").click(function(e) {
// the following is a simple inline `if` statement
// what it says is (this is your element)
// if this.i does not exist, create it equal to one,
// else count it up once
!this['i'] ? this.i=1: this.i++;
$("#pic").html('<img src="/' + this.i + '.JPG" />');
// the following simply shows what `i` currently is
$('h3').text(this.i);
});
p { cursor: pointer; background: #aabb00; padding: 1em .5em; text-align: center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p id="browse-right">Browse Right</p>
<h3></h3>
<div id="pic">
IMG HERE
</div>

Emulate Frameset Separator Behavior

The HTML5 current specification removed the <frameset> tag.
There is a nice feature of <frameset> which is not easy to reproduce without it:
In a frameset, you can change the position of the line separating the frames with the mouse.
How would I provide the same functionality with with using DIVs in JavaScript?
I've come across the following which demonstrates the behavior I'm looking for. However I would like to avoid using JQuery, even though using jQuery should be the preferred way.
After looking at your example fiddle, I can say that this is actually quite easy without jQuery.
All the functions there are just simple innerHTML and style manipulation, and event subscription.
A direct rewrite of that code without jQuery would be:
var i = 0;
document.getElementById("dragbar").onmousedown = function (e) {
e.preventDefault();
document.getElementById("mousestatus").innerHTML = "mousedown" + i++;
window.onmousemove = function (e) {
document.getElementById("position").innerHTML = e.pageX + ', ' + e.pageY;
document.getElementById("sidebar").style.width = e.pageX + 2 + "px";
document.getElementById("main").style.left = e.pageX + 2 + "px";
};
console.log("leaving mouseDown");
};
window.onmouseup = function (e) {
document.getElementById("clickevent").innerHTML = 'in another mouseUp event' + i++;
window.onmousemove = null;
};
So here is the same fiddle with pure JS.
EDIT: As #BenjaminGruenbaum pointed out, overriding the on* properties on a DOM element is not the same as specifying a new event handler.
Overriding properties like onmouseup, onload, onclick on DOM elements is the "old" way, and therefore it was supported in even the stone age of JS. My code above was written like that.
Nowadays the standard way of adding and removing event handlers are addEventListener and removeEventListener. They are not supported in old IE (but this can be worked around).
It let's you attach unlimited number of listeners to the same event and they will not interfere with each other.
So the same functionality can be achieved by:
var i = 0;
function dragBarMouseDown(e) {
e.preventDefault();
document.getElementById("mousestatus").innerHTML = "mousedown" + i++;
window.addEventListener("mousemove", windowMouseMove, false);
console.log("leaving mouseDown");
}
function windowMouseMove(e) {
document.getElementById("position").innerHTML = e.pageX + ', ' + e.pageY;
document.getElementById("sidebar").style.width = e.pageX + 2 + "px";
document.getElementById("main").style.left = e.pageX + 2 + "px";
}
function windowMouseUp(e) {
document.getElementById("clickevent").innerHTML = 'in another mouseUp event' + i++;
window.removeEventListener("mousemove", windowMouseMove, false);
}
document.getElementById("dragbar").addEventListener("mousedown", dragBarMouseDown, false);
window.addEventListener("mouseup", windowMouseUp, false);
Fiddle.
Note that in this case my functions are not anonymous, so a self executing function for scoping would make sense here, if you are not already in function scope.
Here is a horizontal version of #SoonDead's pure and simple answer with a bottom shelf and a horizontal divider.
The result should look like this:
fiddle here
var i = 0;
function dragBarMouseDown(e) {
e.preventDefault();
document.getElementById("mousestatus").innerHTML = "mousedown" + i++;
window.addEventListener("mousemove", windowMouseMove, false);
console.log("leaving mouseDown");
}
function windowMouseMove(e) {
document.getElementById("position").innerHTML = e.pageX + ', ' + e.pageY;
//document.getElementById("main").style.height = e.pageY + 2 + "px";
document.getElementById("dragbar").style.top = e.pageY + 2 + "px";
document.getElementById("bottomshelf").style.top = e.pageY + 17 + "px";
}
function windowMouseUp(e) {
document.getElementById("clickevent").innerHTML = 'in another mouseUp event' + i++;
window.removeEventListener("mousemove", windowMouseMove, false);
}
document.getElementById("dragbar").addEventListener("mousedown", dragBarMouseDown, false);
window.addEventListener("mouseup", windowMouseUp, false);
body, html {
width:100%;
height:100%;
padding:0;
margin:0;
}
#header {
background-color: wheat;
width:100%;
height: 50px;
}
#main {
background-color: BurlyWood;
float: top;
position: absolute;
top:50px;
width:100%;
bottom: 38px;
overflow-y: hidden;
}
#dragbar {
background-color:grey;
width:100%;
float: top;
top:120px;
bottom:0px;
height: 15px;
cursor: row-resize;
position:absolute;
}
#bottomshelf {
background-color: IndianRed;
width:100%;
float: top;
position: absolute;
top:135px;
bottom: 38px;
}
#footer {
background-color: PaleGoldenRod;
width:100%;
height: 38px;
bottom:0;
position:absolute;
}
<div id="header">header <span id="mousestatus"></span>
<span id="clickevent"></span>
</div>
<div id="main">main area:
The bottom shelf will slide over this.
</div>
<div id="dragbar">drag me up or down</div>
<div id="bottomshelf">
<span id="position"></span>
bottom shelf</div>
<div id="footer">footer</div>
I don't have enough reputation to add comment to "SoonDead"s solutions, so I have to do this. :-( The solutions are great and worked out for me, except for IE8
1) The line
e.preventDefault();
has two issues for IE8
the argument "e"vent is not defined.
preventDefault method is not defined for e
So the above line is replaced with:
e = e || window.event;
e.preventDefault ? e.preventDefault() : e.returnValue=false;
The above stopped the errors (and I stopped here since I don't really care about IE8 but do not want error boxes popping up for the hapless user). So yes, in my app IE8 users cannot resize.
However, I did chase it down a little, and found these issues:
Code flow did not enter the onmousemove function
The e.pageX will have to be replaced by e.clientX or e.screenX (depending on your case) since I could not see pageX as a property in the IE8 debugger.
Here are some options discussed on SO.
My personal recommendation would be jQuery Resizable.
As BenjaminGruenbaum said in a comment, jQuery is JavaScript. If you don't want to load the full jQuery library, you'll need to find which parts of the jQuery library you need and pull out the source JavaScript to use. It's certainly doable.

Scroll event background change

I am trying to add a scroll event which will change the background of a div which also acts as the window background (it has 100% width and height). This is as far as I get. I am not so good at jquery. I have seen tutorials with click event listeners. but applying the same concept , like, returning scroll event as false, gets me nowhere. also I saw a tutorial on SO where the person suggest use of array. but I get pretty confused using arrays (mostly due to syntax).
I know about plugins like waypoints.js and skrollr.js which can be used but I need to change around 50-60 (for the illusion of a video being played when scrolled) ... but it wont be feasible.
here is the code im using:-
*
{
border: 2px solid black;
}
#frame
{
background: url('1.jpg') no-repeat;
height: 1000px;
width: 100%;
}
</style>
<script>
$(function(){
for ( i=0; i = $.scrolltop; i++)
{
$("#frame").attr('src', ''+i+'.jpg');
}
});
</script>
<body>
<div id="frame"></div>
</body>
Inside your for loop, you are setting the src attribute of #frame but it is a div not an img.
So, instead of this:
$("#frame").attr('src', ''+i+'.jpg');
Try this:
$("#frame").css('background-image', 'url(' + i + '.jpg)');
To bind a scroll event to a target element with jQuery:
$('#target').scroll(function() {
//do stuff here
});
To bind a scroll event to the window with jQuery:
$(window).scroll(function () {
//do stuff here
});
Here is the documentation for jQuery .scroll().
UPDATE:
If I understand right, here is a working demo on jsFiddle of what you want to achieve.
CSS:
html, body {
min-height: 1200px; /* for testing the scroll bar */
}
div#frame {
display: block;
position: fixed; /* Set this to fixed to lock that element on the position */
width: 300px;
height: 300px;
z-index: -1; /* Keep the bg frame at the bottom of other elements. */
}
Javascript:
$(document).ready(function() {
switchImage();
});
$(window).scroll(function () {
switchImage();
});
//using images from dummyimages.com for demonstration (300px by 300px)
var images = ["http://dummyimage.com/300x300/000000/fff",
"http://dummyimage.com/300x300/ffcc00/000",
"http://dummyimage.com/300x300/ff0000/000",
"http://dummyimage.com/300x300/ff00cc/000",
"http://dummyimage.com/300x300/ccff00/000"
];
//Gets a valid index from the image array using the scroll-y value as a factor.
function switchImage()
{
var sTop = $(window).scrollTop();
var index = sTop > 0 ? $(document).height() / sTop : 0;
index = Math.round(index) % images.length;
//console.log(index);
$("#frame").css('background-image', 'url(' + images[index] + ')');
}
HTML:
<div id="frame"></div>
Further Suggestions:
I suggest you change the background-image of the body, instead of the div. But, if you have to use a div for this; then you better add a resize event-istener to the window and set/update the height of that div with every resize. The reason is; height:100% does not work as expected in any browser.
I've done this before myself and if I were you I wouldn't use the image as a background, instead use a normal "img" tag prepend it to the top of your page use some css to ensure it stays in the back under all of the other elements. This way you could manipulate the size of the image to fit screen width better. I ran into a lot of issues trying to get the background to size correctly.
Html markup:
<body>
<img src="1.jpg" id="img" />
</body>
Script code:
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200) {
// function goes here
$('img').attr('src', ++count +'.jpg');
}
});
});
I'm not totally sure if this is what you're trying to do but basically, when the window is scrolled, you assign the value of the distance to the top of the page, then you can run an if statement to see if you are a certain point. After that just simply change run the function you would like to run.
If you want to supply a range you want the image to change from do something like this, so what will happen is this will allow you to run a function only between the specificied range between 200 and 400 which is the distance from the top of the page.
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200 && topPage < 400) {
// function goes here
$('#img').attr('src', ++count +'.jpg');
}
});
});

Change DIV margin on interval

I am trying to change the margin of each element, using setAttribute.
How can I able to use my variable dist "distance" to decrease value until 10, every after delay "interval"?
var dist=200; var speed = 2000;
function slideLeft(x){
dist--;
slideSet[x].setAttribute("style","margin-right:"+dist+"px;");
setTimeout(slideLeft(x), delay);
}
Take these style and elements for example...
.widiv { margin-right:200px; }
<div>
<div class="widiv" ></div>
<div class="widiv" ></div>
</div>
Thanks a lot.
Here's your code with some changes: See fiddle http://jsfiddle.net/chrismoutray/4p3xX/
var dist = 200, delay = 500,
slideSet = document.getElementsByTagName('div');
function slideLeft(x) {
dist--;
if (dist < 0) return;
slideSet[x].setAttribute("style", "margin-right:" + dist + "px;");
setTimeout(function() {
slideLeft(x);
}, delay);
}
slideLeft(1);
With a few additions to the styling:
.widiv {
margin-right:200px;
float:left;
width: 100px;
border: 1px solid black;
height: 100px; }
The main differences are that when calling setTimeout I'm using a function delegate (function() { <your code here> }) to call the slideLeft method so that x variable is used correctly - I don't think you can pass a statement into setTimeout without doing it this way.
Also in styling the divs I made sure to include a float left other wise the change to margin right doesn't make sense - should this be margin left instead?

Categories

Resources