Background Images changing with a click - javascript

I am trying to change my 4 background images on mouseclick.
At the moment the same image appears 4 times on the screen (1 in each corner).
I would like to have only one image appearing on the whole screen and others replacing it when I click on the current image; and so on and so forth as you click again.
I am unsure what is wrong with my code at the moment.
HTML:
<!DOCTYPE html>
<html lang="fr" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title> CODE </title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script src="js/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/sketch.js"></script>
</head>
<body>
<div id="body" class="imageOne"></div>
</body>
</html>
JS:
var bodyObj,
className,
index;
bodyObj = document.getElementById('body');
index = 1;
className = [
'imageOne',
'imageTwo'
];
function updateIndex() {
if (index === 0) {
index = 1;
} else {
index = 0;
}
}
bodyObj.onclick = function(e) {
e.currentTarget.className = className[index];
updateIndex();
}
CSS:
html, body, #body {
height: 100%;
width: 100%;
}
#body.imageOne {
background-image: url("img1.png");
}
#body.imageTwo {
background-image: url("img2.png");
}
#body.imageTwo {
background-image: url("img3.png");
}
#body.imageTwo {
background-image: url("img4.png");
}

Rather than using classes for each image, it would be good to store them in an array and then change it programmatically. Please find the snippet below.
let imgList = [
'https://dummyimage.com/200x200/000/fff&text=image+1',
'https://dummyimage.com/200x200/000/fff&text=image+2', 'https://dummyimage.com/200x200/000/fff&text=image+3', 'https://dummyimage.com/200x200/000/fff&text=image+4'
];
let currentIndex = 0;
function changeImg() {
$('#body').css('backgroundImage', `url(${imgList[currentIndex]})`);
currentIndex++;
if (currentIndex == imgList.length) currentIndex = 0;
}
changeImg();
$('#body').on('click', changeImg);
#body {
width: 200px;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body" class="imageOne"></div>

Here is another way (using classes as you did):
var bodyObj = document.getElementById('body'),
index = 0,
className = [
'imageOne',
'imageTwo',
'imageThree',
'imageFour'
];
bodyObj.onclick = function(e) {
index = (index + 1) % className.length;
e.currentTarget.className = className[index];
}
html,body,#body { margin: 0; height: 100%; width: 100%; }
#body { background-position: center; background-size: cover; }
#body.imageOne { background-image: url("https://picsum.photos/id/9/536/354"); }
#body.imageTwo { background-image: url("https://picsum.photos/id/3/536/354"); }
#body.imageThree { background-image: url("https://picsum.photos/id/1/536/354"); }
#body.imageFour { background-image: url("https://picsum.photos/id/2/536/354"); }
<div id="body" class="imageOne"></div>

I tried this one which works pretty well!
var index = 0;
var className = ['imageOne',
'imageTwo',
'imageThree',
'imageFour',
'imageFive'];
$(document).ready(function() {
$("#main").on("click", function() {
index = (index + 1) % className.length;
$(this).attr('class', className[index]);
});
});

Related

Javascript - need an image to disappear momentarily while the the other image transitions

**Hi, fellow Developers! I'm in bit of a rut. I am currently working on making an image fade and transition to another image using Javascript. I'm new to code (and stackoverlow) and am still learning how to program - how can I can make the images fade without being apparent in the background?
What I expected the code to do was fade, transition to the second image, and repeat. It
Here is what the code looks like so far.**
======HTML CODE=====
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Image Transition</title>
====CSS======
<style>
body {
text-align: center;
}
h1 {
color: green;
}
img {
position: absolute;
left: 400px;
}
</style>
</head>
<body>
<div id="scroll-image">
<img src="SnugBear_home.png" class="test"/>
<img src="img.png" class="test"/>
<img src="img2.png" class="test"/>
</div>
=======Javascript Code=======
<script>
startImageTransition();
function startImageTransition() {
var images = document.getElementsByClassName("test");
for ( var i = 0; i < images.length; ++i) {
images[i].style.opacity = 1;
}
var top = 1;
var cur = images.length - 1;
setInterval(changeImage, 3000);
async function changeImage() {
var nextImage = (1 + cur) % images.length;
images[cur].style.zIndex = top + 1;
images[nextImage].style.zIndex = top;
images[cur].style.zIndex = top;
images[nextImage].style.zIndex = top + 1;
top = top + 1;
images[cur].style.opacity = 1;
cur = nextImage;
}
function transition() {
return new Promise(function(resolve, reject) {
var del = 0.01;
var id = setInterval (changeOpacity, 10);
function changeOpacity() {
images[cur].style.opacity -= del;
if (images[cur].style.opacity <= 0) {
clearInterval(id);
resolve();
}
}
})
}
}
</script>
</body>
</html>
Fading can be made with animation CSS. Liked the code above and I just added a small code `.animate()'.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Image Transition</title>
<style>
body {
text-align: center;
}
h1 {
color: green;
}
img {
width: 100px;
height: 100px;
position: absolute;
left: 400px;
}
#one {
background-color: red;
}
#two {
background-color: blue;
}
#three {
background-color: green;
}
</style>
</head>
<body>
<div id="scroll-image">
<img src="SnugBear_home.png" class="test" id="one"/>
<img src="img.png" class="test" id="two"/>
<img src="img2.png" class="test" id="three"/>
</div>
<script>
startImageTransition();
function startImageTransition() {
var images = document.getElementsByClassName("test");
for ( var i = 0; i < images.length; ++i) {
images[i].style.opacity = 1;
}
var top = 1;
var cur = images.length - 1;
setInterval(changeImage, 3000);
async function changeImage() {
var nextImage = (1 + cur) % images.length;
images[cur].style.zIndex = top + 1;
images[cur].animate([
{opacity: 1},
{opacity: 0}
], 3000)
images[nextImage].style.zIndex = top;
images[nextImage].animate([
{opacity: 0},
{opacity: 1}
], 3000)
images[cur].style.zIndex = top;
images[nextImage].style.zIndex = top + 1;
top = top + 1;
images[cur].style.opacity = 1;
cur = nextImage;
}
function transition() {
return new Promise(function(resolve, reject) {
var del = 0.01;
var id = setInterval (changeOpacity, 10);
function changeOpacity() {
images[cur].style.opacity -= del;
if (images[cur].style.opacity <= 0) {
clearInterval(id);
resolve();
}
}
})
}
}
</script>
</body>
</html>

jquery draggable, making a div not to go outside of the other div frame

i need a draggable div not to go outside of second div frame, so far i managed to make a "collision" basically returning true or false if draggable div is inside the frame of other div. So the thing now is that i cant get this to work, i was trying to get it to a x = 90(example) when it hits the frame and few more examples , but i just can't get this to work. The draggable div doesn't want to go back to position.
Here is a JSFiddle: https://jsfiddle.net/kojaa/x80wL1mj/2/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Catch a ball</title>
</head>
<body>
<div class="catcherMovableArea" id="catcherMovableArea">
<div id="catcher" class="catcher"></div>
</div>
<script src="script.js"></script>
</body>
</html>
.catcherMovableArea {
position: absolute;
border: 1px solid black;
width: 1900px;
top: 90%;
height: 50px;
}
.catcher {
position: absolute;
width: 250px;
height: 30px;
border-radius: 10px;
background-color: black;
top: 20%;
}
let catcher = $("#catcher");
$(document).mousemove(function(e) {
catcher.position({
my: "left-50% bottom+50%",
of: e,
collision: "fit"
});
let catcherOffset = $(catcher).offset();
let CxPos = catcherOffset.left;
let CyPos = catcherOffset.top;
let catcherYInMovableArea, catcherXInMovableArea = true;
while(!isCatcherYinMovableArea(CyPos)){
catcherYInMovableArea = false;
break;
}
while(!isCatcherXinMovableArea(CxPos)){
catcherXInMovableArea = false;
break;
}
});
function isCatcherYinMovableArea(ypos){
if(ypos < 849.5999755859375 || ypos > 870.5999755859375) {
return false;
} else {
return true;
}
}
function isCatcherXinMovableArea(xpos){
if(xpos < 8 || xpos > 1655 ) {
return false;
} else {
return true;
}
}
By default, the collision option will prevent the element from being placed outside of the window. You want to prevent it from moving outside of a specific element.
To do this, use the within option to select which element should be used for containment.
Example:
let draggable = $("#draggable");
$(document).mousemove(function(e) {
draggable.position({
my: "left-50% bottom+50%",
of: e,
collision: "fit",
within: "#container"
});
});
#container { width: 200px; height: 100px; border-style: solid }
#draggable { width: 50px; height: 50px; background-color: black }
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.0-rc.1/jquery-ui.js"></script>
<div id="container">
<div id="draggable"></div>
</div>

Background Image that covers whole webpage, is responsive and also is chosen randomly

I am trying to create a page that has a background image that uses the css cover property so that it is responsive in the browser but doesn't get distorted but is chosen by random from an array in jQuery.
I don't have much code because this is the only thing that I am doing at the moment, I've been playing around but I don't have much of a handle on jQuery so I don't really know what I am doing! Any help appreciated!
HTML:
<head>
<title>Test</title>
<link href="css/css.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="javascript/jquery.js"></script>
</head>
<body>
<div id="background">
</div>
</body>
CSS:
body {
margin: 0;
}
#background {
width: 100%;
height: 100%;
margin: 0;
background-repeat: no-repeat;
background-size: cover;
background-image: url(backgroundImage)
}
html, body {
overflow: none !important;
overflow-x: none !important;
overflow-y: none !important;
}
jQuery:
var picArr = ['Images/IMG_3764.jpg', 'Images/IMG_3793.jpg', 'Images/IMG_4050.jpg', 'Images/IMG_4323.jpg', 'Images/IMG_4351.jpg', ];
var myNumber = Math.floor(Math.random() * 5);
$(document).ready(function () {
$("background-image").attr('url', picArr[myNumber]);
});
If you want to randomise it, use a setTimeout()
Also, to change the background image on the "background" div, just .css jquery selector like below.
eg
var picArr = ['Images/IMG_3764.jpg', 'Images/IMG_3793.jpg', 'Images/IMG_4050.jpg', 'Images/IMG_4323.jpg', 'Images/IMG_4351.jpg', ];
$(document).ready(function () {
setTimeout(function(){
var myNumber = Math.floor(Math.random() * 5) + 1;
$("#background").css('background-image', 'url('+picArr[myNumber]+')'); //here
}, 3000); // ms of how often you want it to change.
});
Didn't you misstype the selector $("background-image"), isn't this supposed to be $("#background")
var picArr = ['Images/IMG_3764.jpg', 'Images/IMG_3793.jpg', 'Images/IMG_4050.jpg', 'Images/IMG_4323.jpg', 'Images/IMG_4351.jpg', ];
var myNumber = Math.floor(Math.random() * 5);
$(document).ready(function () {
$("#background").attr('url', picArr[myNumber]); //here
});
#background {
width: 100%;
height: 100%;
margin: 0;
background-repeat: no-repeat;
background-size: cover;
background-image: url(backgroundImage)
}
<link href="css/css.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="javascript/jquery.js"></script>
<div id="background">
</div>
I guess this has already been answered now but this was my solution:
var picArr = ['http://lorempixel.com/output/fashion-q-c-640-480-1.jpg', 'http://lorempixel.com/output/animals-q-c-640-480-4.jpg', 'http://lorempixel.com/output/nightlife-q-c-640-480-2.jpg'];
var l = picArr.length;
var myNumber = Math.floor(Math.random() * l);
console.log(myNumber);
$(document).ready(function () {
$("#background").attr('style', 'background: url(' + picArr[myNumber]) + ')';
});
CSS:
html, body {
margin: 0;
height: 100%;
min-height: 100%;
}

Trouble dynamically creating elements with JS

I'm working on a bootcamp and some guys and I have created a group. We are trying to dynamically create html elements using pure JavaScript. The elements are there but we get an error running and we want to be able to go back and use/grab those elements later. Any advice on what we are doing wrong would be much appreciated.
The HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Grid</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="grid"></div>
<script src="js/script.js" type="text/javascript"></script>
</body>
</html>
The js:
(function() {
var grid = document.getElementById("grid");
for (var i = 0; i < 5; i++) {
var temp = document.createElement("DIV");
temp.className = "row";
grid.appendChild(temp);
}
var row = grid.getElementsByClassName("row");
})();
The CSS:
.grid {
height: 100%;
width: 100%;
overflow: auto;
background-color: black;
}
.row {
overflow: auto;
}
.box {
padding: 0;
box-sizing: border-box;
background-color: white;
height: 100px;
float: left;
}
Thanks!
I see no error on your code.
your divs are collected and you can play with them around. take a look to the jsfiddle and open your console. (press F12 or inspect element on right mouse click).
(function() {
var grid = document.getElementById("grid");
for (var i = 0; i < 5; i++) {
var temp = document.createElement("DIV");
temp.className = "row";
grid.appendChild(temp);
}
var row = grid.getElementsByClassName("row");
row[row.length - 1].style.borderColor = "blue";
row[0].style.borderColor = "red";
})();
and the css
.row {
background.color:#f2f2f2;
border: 1px solid #dadada;
margin-bottom:10px;
height:20px;
}
http://jsfiddle.net/hu7a7k0s/

Creating a cropped image slideshow

I am looking to create two side by side image galleries that can be controlled independently of eachother and allow for interesting image combinations.
I have the cropped image code and the 'click to change image' code, i just cant figure out how to combine the two.
Code: http://jsfiddle.net/7ae0chbs/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<style>
.cover {
width: 334px;
height: 500px;
}
.thumbnail {
height: 100%;
background-size: cover;
-moz-background-size: cover;
-webkit-background-size: cover;
background-position: left;
}
.thumbnail2 {
height: 100%;
background-size: cover;
-moz-background-size: cover;
-webkit-background-size: cover;
background-position: right;
}
.clearBoth { clear:both; }
img{
width : 668spx;
height : 500px;
}
</style>
</head>
<body>
<div class="cover" style="float:left;">
<div style="background-image: url(sam_5331.jpg); " class="thumbnail" ></div>
</div>
<div class="cover" style="float:left;">
<div style="background-image: url(sam_5370.jpg); " class="thumbnail2"></div>
</div>
<br class="clearBotnh" />
<img src="sam_5331.jpg" id="imgClickAndChange" onclick="changeImage()" usemap="#SUB15" />
<script>
var counter = 1;
imgClickAndChange.onclick = function(){
if(counter == 0){
document.getElementById("imgClickAndChange").src = "sam_5331.jpg";
counter++;
}
else if(counter == 1){
document.getElementById("imgClickAndChange").src = "sam_0092.jpg";
counter++;
}
else if(counter == 2){
document.getElementById("imgClickAndChange").src = "sam_0150.jpg";
counter = 0;
}
};
</script>
stu
Not sure I'm 100% understanding your end result, but are you wanting the side by side div's backgrounds to change when clicked?
If so, is this what you want? http://jsfiddle.net/u1uostrc/
I just added id's to both of the divs that show the actual images, and set onclicks for them, along with counters for each.
var img1Counter = 0;
var img2Counter = 1;
img1.onclick = function() {
if (img1Counter == 0) {
document.getElementById("img1").style.backgroundImage = "url('http://upload.wikimedia.org/wikipedia/commons/thumb/8/88/Number_1_in_green_rounded_square.svg/2000px-Number_1_in_green_rounded_square.svg.png')";
img1Counter++;
} else if(img1Counter == 1) {
document.getElementById("img1").style.backgroundImage = "url(http://tomreynolds.com/wp/wp-content/uploads/2014/01/2-graphic.png)";
img1Counter++;
} else if(img1Counter == 2) {
document.getElementById("img1").style.backgroundImage = "url(http://upload.wikimedia.org/wikipedia/commons/6/69/VET_3_circle.png)";
img1Counter = 0;
}
}
img2.onclick = function() {
if (img2Counter == 0) {
document.getElementById("img2").style.backgroundImage = "url('http://upload.wikimedia.org/wikipedia/commons/thumb/8/88/Number_1_in_green_rounded_square.svg/2000px-Number_1_in_green_rounded_square.svg.png')";
img2Counter++;
} else if(img2Counter == 1) {
document.getElementById("img2").style.backgroundImage = "url(http://tomreynolds.com/wp/wp-content/uploads/2014/01/2-graphic.png)";
img2Counter++;
} else if(img2Counter == 2) {
document.getElementById("img2").style.backgroundImage = "url(http://upload.wikimedia.org/wikipedia/commons/6/69/VET_3_circle.png)";
img2Counter = 0;
}
}
Hope this helps...

Categories