How to change content of a div - javascript

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.

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'>

How to display one image in loop?

I'm trying to display one image in loop. Knowing the path and image-name are okay is this example, how to display one image in loop, and when the image haven't been found, the browser displays the last right image-name until the image-name is found?
#{int j=1;}
<img src="" />
<script>
(function () {
for (var i = 1; true; i++) {
#{ string file = "/MonitoringN/../bitmaps/" + j + ".png"; bool a = System.IO.File.Exists(file) == true; }
var str = "/MonitoringN/../bitmaps/" + i + ".png";
var b = "#a";
if (b)
{
setInterval(function () { $('img').prop('src', str); }, 1000);
} else {
i--;
#{j--;}
}
#{j++;}
}
});
</script>
Because when I execute this code, I get a blank image, and then I can't see the page is loading.
Thanks a lot!
I think I know what you are trying to do ...
If I understand the question correctly, you have a list of images and you want to try to open them until one of them is found. If an image is NOT found, you want to skip to the next one.
First -- I'd simply for your question by separating the Razor stuff and the Javascript off into very separate pieces. In fact, I'm going to skip Razor entirely.
<html>
<head>
<title>A test</title>
</head>
<body>
<img src="http://x.invalid" id="myImage">
<script>
var imgs = [
"http://x1.invalid/none",
"https://www.google.com/images/srpr/logo11w.png",
"http://thedailywtf.com/Resources/Images/Primary/logo.gif"
];
var imageIndex = 0;
function tryNextImage() {
var img = document.getElementById("myImage");
img.onerror = function() {
imageIndex++;
tryNextImage();
}
img.src = imgs[imageIndex];
}
// start the ball rolling
tryNextImage();
</script>
</body>
</html>

Showing random divs images every time page is load

Lets say I have these images gallery, how do i randomly display the images everytime when i reload the page?
http://creativepreviews.com/fiddle/study/20131007/
Let's say the image will display in the background of the DIV, then the following should do it.
// JS
var imgArray = ["img1.jpg", "cat.jpg", "sky.jpg"]
function randomBg() {
x = Math.random()
y = Math.round(x * 10)
if (imgArray[y] != undefined) {
document.getElementById("blah").style.backgroundImage = "url('" + imgArray[y] + "')"
} else {
document.getElementById("blah").style.backgroundImage = "url('default.jpg')"
}
}
...and the HTML.
<script src="test.js"></script>
<body onload="randomBg()">
<div id="blah"></div>
...or you could replace the style.backgroundImage in the JS with innerHTML = <img src=" etc...
You could do something along these lines (not tested)
var grd = $('#grid');
var imgs = grd.children();
imgs.sort(function(){return (Math.round(Math.random()) - 0.5);});
grd.remove('li');
for(var i=0;i < imgs.length;i++) grd.append(imgs[i]);
In essence what we are doing is getting all the li elements in 'grid' into an array, randomizing them, removing them all from 'grid' and then putting them back in again.
If you had supplied a working fiddle rather than a link to the finished article it would be easier to modify it and provide a more complete solution.

Getting images to change in a for loop in javascript

So far I created an array with 11 images, initialized the counter, created a function, created a for loop but here is where I get lost. I looked at examples and tutorial on the internet and I can see the code is seeming simple but I'm not getting something basic here. I don't actually understand how to call the index for the images. Any suggestions. Here is the code.
<script type="text/javascript">
var hammer=new Array("jackhammer0.gif",
"jackhammer1.gif",
"jackhammer2.gif",
"jackhammer3.gif",
"jackhammer4.gif",
"jackhammer5.gif",
"jackhammer6.gif",
"jackhammer7.gif",
"jackhammer8.gif",
"jackhammer9.gif",
"jackhammer10.gif")
var curHammer=0;
var numImg = 11;
function getHammer() {
for (i = 0; i < hammer.length; i++)
{
if (curHammer < hammer.length - 1) {
curHammer = curHammer +1;
hammer[i] = new Image();
hammer[i].src="poses/jackhammer" +(i+1) + ".gif";
var nextHammer = curHammer + 1;
nextHammer=0;
{
}
}
}
}
setTimeout("getHammer()", 5000);
</script>
</head>
<body onload = "getHammer()";>
<img id="jack" name="jack" src = "poses/jackhammer0.gif" width= "100" height ="113" alt = "Man and Jackhammer" /><br/>
<button id="jack" name="jack" onclick="getHammer()">Press button</button>
Following on what Paul, said, here's an example of what should work:
var hammer=["jackhammer0.gif","jackhammer1.gif","jackhammer2.gif","jackhammer3.gif",
"jackhammer4.gif","jackhammer5.gif","jackhammer6.gif","jackhammer7.gif",
"jackhammer8.gif","jackhammer9.gif","jackhammer10.gif"];
var curHammer=0;
function getHammer() {
if (curHammer < hammer.length) {
document.getElementById("jack").src= "poses/" + hammer[curHammer];
curHammer = curHammer + 1;
}
}
setTimeout("getHammer()", 5000);
The big missing element is that you need to call getElementById("jack") to get a reference to the DOM Image so that you can change it's source. If you're using jQuery or most other JS frameworks, just type $("#jack") to accomplish the same.
I don't understand the need for the for loop at all, just increment the index value [curHammer] each time you click, and reset if it passes your max index length (in this case 11).
Pseudo-Code:
currentHammer = -1
hammers = [ "a1.jpg", "a2.jpg", "a3.jpg"]
getHammer()
{
currentHammer = currentHammer + 1;
if(currentHammer > 2)
currentHammer = 0;
image.src = hammers[currentHammer];
}
a) are you just trying to show an animated gif? If so, why not use Adobe's Fireworks and merge all those gifs into a single gif?
b) you know that the way you have it the display is going to go crazy overwriting the gif in a circle right?
c) you might want to put a delay (or not). If so, make the load new gif a separate function and set a timeout to it (or an interval).
Also, you are being redundant. How about just changing the src for the image being displayed?:
var jackHammer = new Array();
for (var i=0;i<11;i++) { //pre-loading the images
jackHammer[i] = new image();
jackHammer[i].src = '/poses/jackHammer'+i.toString()+'.gif';
} //remember that "poses" without the "/" will only work if that folder is under the current called page.
for (var i=0;i<11;i++) { //updating the image on
document.getElementById('jhPoses').src = jackHammer[i].src;
}
on the document itself,
< img id='jhPoses' src='1-pixel-transparent.gif' width='x' height='y' alt='poses' border='0' />

Categories

Resources