Add Next and Prev Buttons To Rotating Banner - javascript

I'm not knowledgeable in JS and Jquery so I'm really hoping someone here could help me out.
I want my banner to change image on page load or refresh and I found this code:
<script type="text/javascript">
window.onload = function () {
var random = document.getElementById('random');
var pictures = new Array('images/icn_slide-1.jpg','images/icn_slide-2.jpg','images/icn_slide-1.jpg','images/icn_slide-2.jpg');
var numPics = pictures.length;
if (document.images) {
var chosenPic = Math.floor((Math.random() * numPics));
random.style.background = 'url(' + pictures[chosenPic] + ')';
}
}
The script above works pretty well(background image changes every refresh) but now I want to add a previous and next button(actually I already did) so that when viewers click on next/previous it would display another image. Is there a simple way to do this? How do I make my next and previous button work? Any help would be greatly appreciated. Thanks!
This is the only content inside the of my html:
<div id="random" style="width: 1399px; height:515px; margin:auto;">
<div id="slide_control" class="clearfix">
<span id="prev"><img alt="" title="" src="images/icn_nav-arrow2.png" /></span>
<span id="next"><img alt="" title="" src="images/icn_nav-arrow.png" /></span>
</div>
</div>
It's the #random div that changes background image on refresh as of now and I want it just like that. I added the "slide_control" which contained the "prev" and "next" button and what I want them to do is to also change the background-image of #random when they're clicked.
Most JS/JQquery slider and plugins comes with buttons and controllers but they auto-play images and if I disable the autoplay, they don't change banner/background on refresh.
I only want the images/background to randomly change on refresh or change when prev/next buttons are clicked but I don't know how to achieve this.

Here's a basic example of what you are asking for:
<script type="text/javascript">
function rotateImage(idx) {
var random = document.getElementById('random');
if (document.images) {
random.style.background = 'url(' + pictures[idx] + ')';
selectedImage = idx;
}
}
function getNext() {
var nextImage = selectedImage + 1;
if (selectedImage >= numPics) {
nextImage = 0;
}
rotateImage(nextImage);
}
function getPrev() {
var prevImage = selectedImage - 1;
if (selectedImage < 0) {
selectedImage = numPics -1;
}
rotateImage(prevImage);
}
var pictures = new Array('images/icn_slide-1.jpg','images/icn_slide-2.jpg','images/icn_slide-1.jpg','images/icn_slide-2.jpg');
var numPics = pictures.length;
var selectedImage = null;
window.onload = function () {
var chosenPic = Math.floor((Math.random() * numPics));
rotateImage(chosenPic);
document.getElementById('next').onclick = getNext;
document.getElementById('prev').onclick = getPrev;
}
</script>

Related

Is there a way to switch images src back to original after on.click src change event?

I'm a noob working my way to learn JavaScript on my own and using some resources but want to probe things on my own hence trying this thing but it's not working for some reason. Help is appreciated.
The object is to clarify some blurred images by swapping the source. The images are called zero.jpg/zeroblur.jpg, one.jpg/oneblur.jpg and so on... The page loads with blurred image sources until clicked on. I want to write code so that it goes back to original blurred source image after 5 secs.
P.S.: The code in comments is what I've tried to write on my own.
window.onload = init;
function init() {
var blurryPic = document.getElementsByTagName("img");
for (var i = 0; i < blurryPic.length; i++) {
blurryPic[i].onclick = clarify;
// setTimeout(resetPic, 5000);
}
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
}
// function resetPic(eventObj) {
// var pic = eventObj.target;
// var id = pic.id;
// id = "images/" + id + "blur.jpg";
// pic.src = id;
// }
It's better with CSS: your image stays the same and you only toggle a class, the class making your image blur.
document.getElementById("clickImg").addEventListener("click", function() {
this.classList.toggle("blurImg")
})
.blurImg {
-webkit-filter: blur(5px); /* Safari 6.0 - 9.0 */
filter: blur(5px);
}
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
If what you want is really to be able to reset the original image, I think it's better to stock it in a specific attribute, like this:
document.getElementById("reset").addEventListener("click", function() {
document.getElementById("clickImg").src = document.getElementById("clickImg").getAttribute('origSrc')
})
var imgs = [
'https://vignette.wikia.nocookie.net/spongebob/images/d/d7/SpongeBob_stock_art.png/revision/latest?cb=20190921125147',
'https://static.vecteezy.com/system/resources/previews/000/072/351/non_2x/spongebob-squarepants-vector.jpg',
'https://upload.wikimedia.org/wikipedia/en/c/c7/BattleForBikiniBottom.jpg'
]
document.getElementById("random").addEventListener("click", function() {
document.getElementById("clickImg").src = imgs[Math.floor(Math.random() * 3)]
})
<input type="button" value="RESET" id="reset" />
<input type="button" value="RANDOM" id="random" /><br/>
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" origSrc="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
I used an if statement for this to check if the first loaded image file was present or not. Then use the attribute src for the file. Here's an example.
#javascript
function magicChanger(){
var myImage = document.getElementById("emailImage")
if (myImage.getAttribute("src") == "first loaded image"){
myImage.setAttribute("src", "second image")
}
else{
myImage.setAttribute("src", "first loaded image")
}
}
#html element
<button id = "emailButton" onclick="magicChanger()">
<img id="emailImage" src="{% static 'GoEnigmaPics/emailIcon.png' %}" alt="email">
</button>
Thanks for all the answers! I wanted to get it done in JS only so CSS wouldn't work. Appreciate the answers and will definitely incorporate in future projects!
P. S. This is what got it done in the end.
window.onload = init;
function init() {
var blurryPics = document.getElementsByTagName("img");
for (var i = 0; i < blurryPics.length; i++) {
blurryPics[i].onclick = clarify;
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
setTimeout(reBlur, 3000, pic);
}
function reBlur(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + "blur.jpg";
pic.src = id;
}
Please try this code,To Is there a way to switch images src back to original after on.click src change event?
It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault();
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
return false;
});
});
I hope this code will be useful.
Thank You.

display series of images on button click

is it possible to display 3 images one after another at each button click using a array in JavaScript?
I have an array called
var images = ["image1.jpg","image2.jpg","image3.jpg"]
The way I need the website to load is for the first picture to already be there. Then when I click on the button I want the next picture to be displayed however replacing the image that was there before. I want this to repeat throughout the entire, so when I click on the button, and if the image being displayed was image3, then image1 should be displayed.
I want to share the code I have so far however I don't know where to start. the only code i have is the layout and a variable.
var images = ["image1.jpg","image2.jpg","image3.jpg"]
Try like this.Use 'document.querySelector' do select your button.On clicking button appen images using forEach in body.
var button = document.querySelector('#show');//selects your button
button.addEventListener('click',function(){ // handle click event
var images = ["image1.jpg","image2.jpg","image3.jpg"];//array of valid images
images.forEach(function(image){
img = document.createElement('img');//creates a img element
img.src = image;//sets src of img tag
document.body.appendChild(img)//appends into body
});
});
<button id="show">
Show images
</button>
Pure JS solution.
var images = ["http://placehold.it/350x150", "http://placehold.it/250x150", "http://placehold.it/150x150"];
var elem = document.getElementById('img');
var i = 0;
window.onload = function() {
elem.setAttribute("src", images[i]);
}
elem.addEventListener('click', function() {
(i < images.length-1) ? i++ : i = 0;
this.setAttribute("src", images[i]);
});
<img src='' id='img'>
jQuery solution.
var images = ["http://placehold.it/350x150", "http://placehold.it/250x150", "http://placehold.it/150x150"];
var i = 0;
$(document).ready(function() {
$('#img').attr('src', images[i]);
});
$('#img').click(function() {
(i < images.length-1) ? i++ : i = 0;
$('#img').attr('src', images[i]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src='' id='img'>

Javascript Image toggle/switcher triggered with a button: How can I get the button text to change

So I have been in the process of having an image switcher to toggle images. What I am doing is having 2 images of the same size that are displaying a clean and labeled version. Simple right? Here is what I have so far:
<button id="button-switch"> Hide/Show Redlines</button><script>(function()
{'use strict';function init(){var el=document.getElementById('deconstructed');
document.getElementById('button-switch').onclick=function(){el.id=='deconstructed'?(el.id='t-b',el.
// PLACE CLEAN IMAGE HERE //////////////
src='_images/clean_image.png',el.alt='my t-b'):(el.id='deconstructed',el.
// PLACE *LABELED* IMAGE HERE //////////////
src='_images/labeled_image.png',el.alt='my deconstructed');}}window.addEventListener('load',init,false);})();</script>
<!-- PLACE *LABELED* ONE MORE TIME HERE
--> <div><img id="deconstructed"
src="_images/labeled_image.png"
alt="my deconstructed"></div>
In this code, the text on the button is the same. I by no means are decent at Javascript and I am amazed I was able to get this series of things to cooperate. Any pointers?
Hi firstly write clean code so that everyone understands.
<input type='button'
id="button-switch"
value='Hide/Show Redlines' / >
<script>(function () {
'use strict';
function init() {
var el = document.getElementById('deconstructed');
var button = document.getElementById('button-switch');
button.onclick = function () {
el.id == 'deconstructed' ? (el.id = 't-b', el.src = '_images/clean_image.png', el.alt = 'my t-b',
button.value = 't-b'
)
: (el.id = 'deconstructed', el.src = '_images/labeled_image.png', el.alt = 'my deconstructed',
button.value = ' Hide/Show Redlines');
}
}
window.addEventListener('load', init, false);
})();
</script>
< !--PLACE * LABELED * ONE MORE TIME HERE -- >
< div > < img id = "deconstructed" src = "_images/labeled_image.png" alt = "my deconstructed" > < / div >
hope this helps...

I can change background images, but how to print link?

I am using JavaScript to randomly change the background image upon refresh. What I have been wanting to do is then take the current background-image url and paste it in a certain div within
so that people can download the image.
The background image script works and is as follows:
var totalCount = 3;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'bgimages/'+num+'.jpg';
document.body.style.backgroundRepeat = "repeat";// Background repeat
}
Sorry if this is easy but I haven't been able to figure out how to do it! Can anyone point me in the right direction?
Let's assume you have this link somewhere in your document and you want it to point to the current background image:
<a href='#' id='bgDownload'>Download background image</a>
The following function changes now the "href"-attribute of the link to the current background and the background itself:
var totalCount = 3;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'bgimages/'+num+'.jpg';
document.body.style.backgroundRepeat = "repeat";// Background repeat
// change link
document.getElementById("bgDownload").href = 'bgimages/'+num+'.jpg';
}
I hope it helps...
Put a DIV on your page in the HTML, and switch the content using...
document.getElementById("[ID of DIV]").innerHTML = '' + [text_var] + '';
Something like this...
document.getElementById("[ID of DIV]").innerHTML = 'Image #' + num + '';
Try this
<a href='javascript:window.location.href=document.body.background'>
Download Background
</a>
try this :  
  
function downloadImage{
window.open(document.body.background,'_blank');
}

How to change content of a div

I know this question has been asked before, but if someone could explain in greater detail it would be awesome. I have a div and a table and an image inside this div. I am making a image gallery, so I have two links forward and back, how do I make these links change the image, or rather all the content inside the div. I am very new to javascript, actually I know nothing at all about it, if I could get a step by step instruction that would be awesome, I have tried so of the other post codes but can not get it to work, so I have no idea what I am doing wrong.
Sample HTML:
<html>
<head><title>Dummy page</title></head>
<body>
<div id="divID">
<img id="backImg" src="http://test.com/sample.jpg">
</div>
</body>
</html>
To change the whole div:
var div = document.getElementByID('divID');
div.innerHTML = "<b>This is some html</b>";
To just change the image:
var img = document.getElementByID('backImg');
img.src = "http://www.host.com/image.jpg';
Here's a good example that I made that might help. Try it out -- http://jsfiddle.net/SuperBoi45/XMSGe/
Here's the code for a quick look:
HTML:
<button id="before">Previous</button>
<button id="next">Next</button>
<div id="imageGallery"></div>
JavaScript:
function $(id) {
return document.getElementById(id);
}
var foward = null,
back = null,
images = [
"http://www.toxel.com/wp-content/uploads/2009/04/conceptcar04.jpg",
"http://politicolnews.com/wp-content/uploads/2010/01/bill-gates-car.jpg",
"http://www.youthedesigner.com/wp-content/uploads/2008/05/car-wallpapers19.jpg",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-555c9ae9cfd364db5307b2e8d717a00d",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-01589fb639efec5433a3e30a8a8dd449",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-31f8cbd6627edc1ba9ef2828f3423fdf",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-0f47a0c2db85b5d7c134d41bcdc65b2e",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-739fd589778207e542a6e31873a24433",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-6056a5df58462ea4951a2b328243b7a2",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-59028363fc0f7d0ee7aa1ebc5e72713a",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-eb09864be7a1fbe7e821bc1ee08c3a8b",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-50bd88090e05a452bba67d510ba4a0cc",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-191b37eea296e90a242d24db90824c5c"
];
var img = new Image();
for (var i = 0; i < images.length; i++) { // caching the images for performance boost
img.src = images[i];
}
var image = {
count: -1,
next: function() {
if (image.count == (images.length) - 1) return false;
image.count += 1;
$('imageGallery').innerHTML = "<img src=\"" + images[image.count] + "\"\/>";
},
previous: function() {
if (image.count <= 0) return false;
image.count -= 1;
$('imageGallery').innerHTML = "<img src=\"" + images[image.count] + "\"\/>";
}
};
foward = image.next;
back = image.previous;
$('next').addEventListener("click", foward);
$('before').addEventListener("click", back);
The best thing about this is that all you have to do is add a new image URL to the array and it will still work.
If you want to change the images but not all the content in the div, I'd recommend putting in another div outside the image gallery.

Categories

Resources