Randomize images when refreshing page js html - javascript

Here is a code that should render images randomly using DIV HTML rather than document.write, does anyone have an idea?
<script>
var theImages = new Array()
//Random-loading images
theImages[0] = '/img/pirc/hostnger-he.png' // replace with names of images
theImages[1] = '/img/pirc/hostnger-en.png' // replace with names of images
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
if(whichImage==0){
$('.hostnger').html('<img class="hostnger" src="'+theImages[whichImage]+'">')
}
else if(whichImage==1){
$('.hostnger').html('<img class="hostnger" src="'+theImages[whichImage]+'">')
}
}
</script>
<div class="hostnger"></div>
Randomize images when refreshing the pageenter code here

Where are you actually calling the showImage function?
You should add
showImage();
somewhere.
Are you including jQuery?
$('.hostnger')
Is a jQuery call and you are not including jQuery anywhere.

Related

I don't how why my backgroundImage doesn't work

Why does my banner doesn't change her background? Please help me.
When I run the file the console tells me:
Uncaught TypeError: flechedroite.addEventListener is not a function
I really don't understand. I'm a beginner in Javascript so please explain me with kind words how I can fix this error :)
var flechedroite = document.getElementsByClassName('fa-arrow-right');
var flechegauche = document.getElementsByClassName('switch-left');
var banner = document.getElementById('banner');
var images = [];
var changeBackground = function (bElement, bUrl) {
return bElement.style.backgroundImage = "url(" + bUrl + ")";
}
//image list
images[0] = 'images/image1.jpg';
images[1] = 'images/image2.jpg';
images[2] = 'images/image3.jpg';
flechedroite.addEventListener('click', function() {
for (var i = 0; i < images.length; i++) {
changeBackground(document.body, images[i]);
}
})
addEventListener should be called in window.onload or in $(document).ready()
Since getElementsByClassName returns an array, you need to use array index with flechedroite to add an event listener. i.e. flechedroite[0].addEventListener('click', function() {...});
You are calling changeBackground function in a loop to set the background image, effectively you will see only the last image from the array being set as background.
JS Code
var images = [];
var changeBackground = function (bElement, bUrl) {
return bElement.style.backgroundImage = "url("+bUrl+")";
}
//image list
images[0] = 'https://www.gettyimages.ie/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg';
images[1] = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTOGUhZo0Qe81U5qY_Z-seXgsD79LEEet832TVOlLMOEy10ZPsV';
images[2] = 'https://cdn.pixabay.com/photo/2016/06/18/17/42/image-1465348_960_720.jpg';
window.onload = function(){
var flechedroite = document.getElementsByClassName('fa-arrow-right');
var flechegauche = document.getElementsByClassName('switch-left');
var banner = document.getElementById('banner');
var currentImageIndex = 0;
flechedroite[0].addEventListener('click', function() {
currentImageIndex = (currentImageIndex+1)%images.length;
changeBackground(document.body, images[currentImageIndex]);
})
}
The function getElementsByClassName returns a HTMLCollection, which is an array like structure that can contain multiple elements. So you need to use an index to access the elements contained in it.
So flechedroite.addEventListener results in an error but flechedroite[0].addEventListener should work
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName
if you use 'getElementsByClassName' and you want to add an 'addEventListener', you can not do it in a 'generic' way: "flechedroite.addEventListener ('click', function () {}". You have to do this for each element:
var flechedroite = document.getElementsByClassName('fa fa-arrow-right');
//flechedroite contains all the elements that have the 'fa fa-arrow-right' classes
//on each element you have to add the "addEventListener"
for (var i = 0; i < flechedroite.length; i++) {
flechedroite[i].addEventListener('click', function() {
alert('flechedroite');
});
}
basic example JSFiddle1
a more advanced example
JSFiddle2

change HTML code for fading background replacing images

This is my HTML code:
<html>
<head>
<script language="JavaScript">
<!--
// Set speed (milliseconds)
var speed = 4000
// Specify the image files
var Pic = new Array() // don't touch this
// to add more images, just continue
// the pattern, adding to the array below
Pic[0] = 'img_1.jpg'
Pic[1] = 'img_2.jpg'
Pic[2] = 'img_3.jpg'
Pic[3] = 'img_4.jpg'
// =======================================
// do not edit anything below this line
// =======================================
var t
var j = 0
var p = Pic.length
var preLoad = new Array()
for (i = 0; i < p; i++){
preLoad[i] = new Image()
preLoad[i].src = Pic[i]
}
function runBGSlideShow(){
if (document.body){
document.body.background = Pic[j];
j = j + 1
if (j > (p-1)) j=0
t = setTimeout('runBGSlideShow()', speed)
}
}
//-->
</script>
</head>
<body onload="runBGSlideShow()">
</body>
</html>
I tried everything I know to change it so the pictures will fade when replacing but I didn't succeed.
If you can I will appreciate it if you will add to the HTML code (if can't it's ok to add css )
Please look and see if you can help me.
Why reinvent the wheel?
There's a beautiful jQuery plugin that does this already
http://srobbin.com/jquery-plugins/backstretch/

ondragstart on an array of elements dynamically in javascript

I have an array of image elements,
var im = ["im1","im2"]; // from db or local drive
Then creating the images dynamically as:
var l = imagelist.length;
for (var i = 0; i < l; ++i) {
if (i in im) {
var s = im[i];
var img = document.createElement("img");
img.src = s;
img.width = width;
img.draggable = true;
var body = document.getElementById("body");
body.appendChild(img);
this.addEventListener('ondragstart', function(event) {
alert(event.target.id);
event.dataTransfer.setData('text/plain', event.target.id);
});
}
While the ondragstart event fires, but alert(event.target.id); shows blank.
That's the reason, the drag and drop functionality is not working for an array of images created dynamically .
Although tried dragging with a single image tag <img> which works absolutely fine, but the array of images doesn't work in this way.
Any solution for this?
You haven't assigned an id to any of your elements.
Something like this should do the trick:
var img = document.createElement("img");
img.src = s;
img.id = "image_" + i;
// The rest of your assignments and code...

Easy image rotating gallery

I have this image-rotating-script that i cannot get to work in any major browser.
What the JS does is to show a random image on pageload.
Here's my code:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
<!-- Begin
var theImages = new Array();
theImages[0] = 'img/rot/forside/FrontReklame1.jpg';
theImages[1] = 'img/rot/forside/FrontReklame2.jpg';
var j = 0;
var p = theImages.length;
var preBuffer = new Array();
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
};
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write('<img src="'+theImages[whichImage]+'" alt="Se vores hingste!" />')
};
// End -->
</script>
What i use to call the image:
<script type="text/javascript">
<!-- Begin
showImage();
// End -->
</script>
This code doesn't show any image live on the net and sometimes it doesn't when i test the page locally?! What am i missing here?
First of all, jquery is not needed in your code.
¿What is the purpose of var j?
Probably you are running showImage() in Header so you can't see the picture.
Try this:
function showImage(){
var selectedImage = preBuffer[whichImage];
selectedImage.alt = "Se vores hingste!";
// Using appendChild instead of document.write
document.body.appendChild(selectedImage);
};

Showing an image from an array of images - Javascript

I have a large image which is shown on my homepage, and when the user clicks the "next_img" button the large image on the homepage should change to the next image in the array.
However, the next arrow when clicked does nothing, and the main image on the homepage does not change.
I need to do this in javascript.
In the HTML:
<!--Main Content of the page -->
<div id="splash">
<img src="images/img/Splash_image1.jpg" alt="" id="mainImg">
</div>
<div id="imglist">
<img src="images/next_img.png" alt="">
And then in the javascript file:
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'images/img/Splash_image1.jpg';
imgArray[1] = new Image();
imgArray[1].src = 'images/img/Splash_image2.jpg';
imgArray[2] = new Image();
imgArray[2].src = 'images/img/Splash_image3.jpg';
imgArray[3] = new Image();
imgArray[3].src = 'images/img/Splash_image4.jpg';
imgArray[4] = new Image();
imgArray[4].src = 'images/img/Splash_image5.jpg';
imgArray[5] = new Image();
imgArray[5].src = 'images/img/Splash_image6.jpg';
/*------------------------------------*/
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0;i<imgArray.length;i++)
{
if(imgArray[i] == img)
{
if(i == imgArray.length)
{
var j = 0;
document.getElementById(element).src = imgArray[j].src;
break;
}
else
var j = i + 1;
document.getElementById(element).src = imgArray[j].src;
break;
}
}
}
Any help would be appreciated. Thanks.
Just as Diodeus said, you're comparing an Image to a HTMLDomObject. Instead compare their .src attribute:
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'images/img/Splash_image1.jpg';
imgArray[1] = new Image();
imgArray[1].src = 'images/img/Splash_image2.jpg';
/* ... more images ... */
imgArray[5] = new Image();
imgArray[5].src = 'images/img/Splash_image6.jpg';
/*------------------------------------*/
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src) // << check this
{
if(i === imgArray.length){
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i+1].src;
break;
}
}
}
Here's a somewhat cleaner way of implementing this. This makes the following changes:
The code is DRYed up a bit to remove redundant and repeated code and strings.
The code is made more generic/reusable.
We make the cache into an object so it has a self-contained interface and there are fewer globals.
We compare .src attributes instead of DOM elements to make it work properly.
Code:
function imageCache(base, firstNum, lastNum) {
this.cache = [];
var img;
for (var i = firstNum; i <= lastnum; i++) {
img = new Image();
img.src = base + i + ".jpg";
this.cache.push(img);
}
}
imageCache.prototype.nextImage(id) {
var element = document.getElementById(id);
var targetSrc = element.src;
var cache = this.cache;
for (var i = 0; i < cache.length; i++) {
if (cache[i].src) === targetSrc) {
i++;
if (i >= cache.length) {
i = 0;
}
element.src = cache[i].src;
return;
}
}
}
// sample usage
var myCache = new imageCache('images/img/Splash_image', 1, 6);
myCache.nextImage("foo");
Some advantages of this more object oriented and DRYed approach:
You can add more images by just creating the images in the numeric sequences and changing one numeric value in the constructor rather than copying lots more lines of array declarations.
You can use this more than one place in your app by just creating more than one imageCache object.
You can change the base URL by changing one string rather than N strings.
The code size is smaller (because of the removal of repeated code).
The cache object could easily be extended to offer more capabilities such as first, last, skip, etc...
You could add centralize error handling in one place so if one image doesn't exist and doesn't load successfully, it's automatically removed from the cache.
You can reuse this in other web pages you develop by only change the arguments to the constructor and not actually changing the implementation code.
P.S. If you don't know what DRY stands for, it's "Don't Repeat Yourself" and basically means that you should never have many copies of similar looking code. Anytime you have that, it should be reduced somehow to a loop or function or something that removes the need for lots of similarly looking copies of code. The end result will be smaller, usually easier to maintain and often more reusable.
Also, when checking for the last image, you must compare with imgArray.length-1 because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:
if(i == imgArray.length-1)
This is a simple example and try to combine it with yours using some modifications. I prefer you set all the images in one array in order to make your code easier to read and shorter:
var myImage = document.getElementById("mainImage");
var imageArray = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg",
"_images/image4.jpg","_images/image5.jpg","_images/image6.jpg"];
var imageIndex = 0;
function changeImage() {
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex = (imageIndex + 1) % imageArray.length;
}
setInterval(changeImage, 5000);
Here's your problem:
if(imgArray[i] == img)
You're comparing an array element to a DOM object.
<script type="text/javascript">
function bike()
{
var data=
["b1.jpg", "b2.jpg", "b3.jpg", "b4.jpg", "b5.jpg", "b6.jpg", "b7.jpg", "b8.jpg"];
var a;
for(a=0; a<data.length; a++)
{
document.write("<center><fieldset style='height:200px; float:left; border-radius:15px; border-width:6px;")<img src='"+data[a]+"' height='200px' width='300px'/></fieldset></center>
}
}

Categories

Resources