JavaScript Slideshow using onload and an image swapping function - javascript

My slideshow flips through images but one of them flips through the wrong image. Can someone please look through my code and find what I can't seem to find!Here is the html:
<div id="serv_tims">
<div id="serv_d"><img name='slide' src='http://jjoli.weebly.com/uploads/1/8/6/0/18608386/1651756_orig.png'/></div>
<div id="serv_t"><img name='slide2' src='http://jjoli.weebly.com/uploads/1/8/6/0/18608386/6848746_orig.png'/></div>
<div id="serv_m"><img name='slide3' src='http://jjoli.weebly.com/uploads/1/8/6/0/18608386/3044861_orig.png'/></div>
</div>
Here is the css:
#serv_tims{
border:solid 4px #0276FD;
height:300px;
width:300px;
position:static;
float:right;
clear:right;
margin:0 0.5% 0 0;
}
#serv_d,#serv_t,#serv_m{
height:100px;
width:300px;
}
Here is my javascript:
var i = 0;
var path = new Array();
path[0]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/1651756_orig.png";
path[1]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/6795103_orig.png";
path[2]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/8269055_orig.png";
function swapImage(){
document.slide.src = path[i];
if(i < path.length - 1){ i++;} else{i = 0;}
setTimeout("swapImage()",2000);
}
var j = 0;
var path2 = new Array();
path2[0]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/6848746_orig.png";
path2[1]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/5983713_orig.png";
path2[2]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/5808905_orig.png";
function swapImage2()
{
document.slide2.src = path[j];
if(j < path2.length - 1){ j++;} else{j = 0;}
setTimeout("swapImage2()",2000);
}
var k = 0;
var path3 = new Array();
path3[0]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/3044861_orig.png";
path3[1]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/3044861_orig.png";
path3[2]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/3044861_orig.png";
function swapImage3()
{
document.slide3.src = path3[k];
if(k < path3.length - 1){ k++;} else {k = 0;}
setTimeout("swapImage3()",2000);
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(swapImage);
addLoadEvent(swapImage2);
addLoadEvent(swapImage3);

Allright I can propose you very simple solution to create your own slideshow
firstly assume that we want to have 5 images in our slide Show .
<div id="main_frame">
<div id="slide_frame">
<div class="imdiv"><img src="1.jpg" class="imgs" /></div>
<div class="imdiv"><img src="2.jpg" class="imgs" /></div>
<div class="imdiv"><img src="3.jpg" class="imgs" /></div>
<div class="imdiv"><img src="4.jpg" class="imgs" /></div>
<div class="imdiv"><img src="5.jpg" class="imgs" /></div>
</div>
</div>
the most important thing is the frame must be overflow:hidden and for instance your the width
your each frame is 500px so the width of the mainframe must be 500px and the witdh of slide frame
must be 500*5=2500px allright
<style>
#main_frame {border:1pxsolid;black;width:500px;height:300px;overflow:hidden;position:relative;}
#slide_frame {border:0px solid transparent;width:2500px;height:300px;position:relative;}
.imgs {width:500px;border:0px;height:300px;position:relative;}
</style>
then you need to have the library of jquery
as:
you will add this library into head tags
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
then write this javascript code
<script type="text/javascript">
$(document).ready(function(){
var slide=500;
var counter=0;
setInterval(function(){
var s=slide*counter;
$("#slide_frame").animate({left:s},600);
counter+=1;
if(counter==5)
counter=0;
},500);
});
</script>
add this javascript code declared upward into head tag .you do not need to call it will start
automatically
Good Luck

I run your code in a fiddle and this is not an image slide show, those are just text. You shouldnt use those kinda concept with images. It'll only make things messy. Here an example for what youre trying to achieve.
<div id="serv_tims">
<div>SUNDAY<br>MORNING</div>
<div>10:00 AM</div>
<div>GOD<br>LOVES YA</div>
</div>
js:
var i = 1;
var text = [
["SUNDAY<br>MORNING","10:00 AM","GOD<br>LOVES YA"],
["SUNDAY<br>EVENING","05:00 PM","GOD<br>LOVES YA"],
["SUNDAY<br>NIGHT","11:00 PM","GOD<br>LOVES YA"]
];
var st = document.getElementById("serv_tims");
setInterval(function(){
for(var j = 0; j < 3; j++){
st.children[j].innerHTML = text[i][j];
}
i = (i < (text.length - 1)) ? (i + 1) : 0;
},3000);
As you can see, you can just edit text array whatever the way you need.
FIDDLE

I see my problem!
document.slide2.src = path[j];
should be
document.slide2.src = path2[j];
Sorry!

One more thing the code I wrote for you is static.If you want to have new images to your
slide shows
For instance the I wrote was only for 5 images.However you can add more.But in order to do
this, you need expand the width of slide_frame when you add a new image every time.And append
the image into slide_frame div.If you want further info I can send you a code snippet that I
had written before
Good Luck

Related

querySelectorAll is not working with data-srcset

I want to apply a class to all the horizontal imgs on the website.
I'm trying to use this function below but it doesn't work.
Any help would be greatly appreciated.
$(function() {
var images = document.querySelectorAll('[data-srcset]');
for (var i = 0; i < images.length; i++) {
if (images[i].naturalWidth > images[i].naturalHeight) {
$(images[i]).addClass('horizontal');
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" data-srcset="https://cdn.pixabay.com/photo/2015/02/18/11/50/mountain-landscape-640617_960_720.jpg" alt=landscape>
That is because the data:... image you provide is 1x1 and so the check for images[i].naturalWidth > images[i].naturalHeight fails.
Keep in mind that if you use the srcset attribute (instead of data-srcset) which is the default it will work as expected (but you need to use the load event of the page).
$(window).load(function() {
var images = document.querySelectorAll('[srcset]');
for (var i = 0; i < images.length; i++) {
if (images[i].naturalWidth > images[i].naturalHeight) {
$(images[i]).addClass('horizontal');
}
}
})
.horizontal{border:10px solid OliveDrab;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" srcset="http://www.dummyimage.com/400x200" alt=landscape>
<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" srcset="http://www.dummyimage.com/200x210" alt=landscape>
It's better to replace alt=landscape with alt="landscape".
both
var images = document.querySelectorAll('[data-srcset]');
and
var images = $('[data-srcset]');
works for me.
Your problem is if statement is not true. it's always go to else.
Try update your if statement by the following code.
if (images[i].naturalWidth > images[i].naturalHeight) {
$(images[i]).addClass('horizontal');
console.log(images[i]);
} else {
console.log('else');
}
You'll see that it's always go to else.

variable inside getelementbyid in javascript not working

I want to reuse an image swap function on multiple divs, but the function is not acknowledging the adbox variable on the var rotator = getelementbyid(adbox).
window.onload = animatez(animate);
the animatez function should pass "animate" which is the div id to getelementbyid inside the function.
function animatez(adbox) {
var adbox;
var rotator = document.getElementById(adbox);
var images = rotator.getElementsByTagName("img");
var counter = 1;
setInterval(function () {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none"; }
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;}
}, 1000);
};
window.onload = animatez(animate);
<style>
#animate { width:200px; height:200px; background-color:transparent;
margin:auto; position:absolute;
}
img {width:200px; height:200px; display:none;}
</style>
<body>
<div id="animate">
<img src="surveyfunny.png">
<img src="myanswertoasurveyquestion.png">
<img src="funny-wheredoyoulive.png">
<img src="funnysurveyquestion2.png">
<img src="funnysurveyquestion.png">
</div>
You need give the function a string parameter. Without quote the animate is undefined, javascript throw the error.
see https://jsfiddle.net/pconline2046/u5cbwpuL/3/#
window.onload = function(){
animatez('animate');
};
window.onload needs to be set equal to a function, not the result of calling your animatez function. You could do something like this.
window.onload = function(){
animatez('animate');
};
Also notice that you need to pass a string to your animatez function so I have quoted animate.
Edit: Like some other answers have stated you also should remove the
var adbox;
line in your function.
Why do you have adbox var defined twice? Once at function animatez(adbox) { and again at var adbox...?

making a div the same size as an img pure JavaScript

fiddle:
http://jsfiddle.net/ue7pq/
and the equivalent jQuery fiddle:
http://jsfiddle.net/Ldn9P/
html:
<div class="project-box">
<img src="img/ifix.jpg" class="thumbnail img-responsive">
<div class="hover-box">
<h2>TITLE</h2>
<p>Description of logos that we've made</p>
</div>
</div>
js:
window.onload = function(){
var project = document.getElementsByClassName('project-box');
img = project[0].getElementsByTagName('img');
box = document.querySelectorAll('div.project-box div.hover-box');
imgWidth = img[0].offsetWidth;
imgHeight = img[0].offsetHeight;
console.log(imgWidth);
console.log(imgHeight);
box.style.width = imgWidth+'px';
box.style.height = imgHeight+'px';
};
I'm trying to make the hover-box the same width and height as the img. I'm trying to keep this as pure javascript I made the mistake of learning jQuery first and not JavaScript so now I'm trying to teach myself JavaScript having some issues. The console log says that hoverbox is undefined
error message in console.log:
Uncaught ReferenceError: hoverBox is not defined main.js: 4
350
180
Uncaught TypeError: Cannot set property 'width' of undefined
querySelectorAll returns a list of elements, but you're treating it as if it references a single element.
I suggest grabbing a list of the project boxes, then looping them and resizing each. That way, if there are more than one on the page then they will all be affected. This would be like doing this in jQuery: $('.project-box').each(function () { ... });
var project_boxes = document.getElementsByClassName('project-box');
for (var i = 0, len = project_boxes.length; i < len; i++) {
var img = project_boxes[i].querySelectorAll('img.thumbnail');
var box = project_boxes[i].querySelectorAll('div.hover-box');
if (box.length > 0 && img.length > 0) {
box[0].style.width = img[0].offsetWidth+'px';
box[0].style.height = img[0].offsetHeight+'px';
}
}
Try it: http://jsfiddle.net/EsJ4k/ (note: images not present, so code results in 0px height and width)
Documentation
querySelectorAll - https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
getElementsByClassName - https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName
HTML
<div class="project-box">
<img src="http://www.samdeveloper.com/images/sam_devloperr.jpg" class="thumbnail img-responsive">
<div class="hover-box">
<h2>TITLE</h2>
<p>Description of logos that we've made</p>
</div>
</div>
CSS
.project-box{position:relative; width:100%;}
.project-box .hover-box{position:absolute; bottom:0; width:100%; background-color:rgba(0,0,0,.5); display:none;}
jQuery
$(function(){
$(".thumbnail").css("width","100%");
$(".project-box").hover(function(){
$(".hover-box").fadeIn(1000);
},function(){
$(".hover-box").fadeOut(1000);
});
});
Online demo for Click Here
window.onload = function(){
var project = document.getElementsByClassName('project-box');
img = project[0].getElementsByTagName('img')[0];
box = document.querySelectorAll('div.project-box, div.hover-box');
imgWidth = img.offsetWidth;
imgHeight = img.offsetHeight;
for(var i = 0; i < box.length;i++){
box[i].style.width = imgWidth+"px";
box[i].style.height = imgHeight+"px";
}
};

Image-loaded-show function by javascript in mobile browser

I'am using the following javascript code to implement image-loaded-show function in mobile web browser (supporting HTML5). Image-loaded-show means that before the image is completely loaded, the width and height is 0, namely it willn't show and occupy any space.
Now the problem is that the images will not show until all the images are loaded.
What I need is that the iamge in the page is seperate, once loaded, the image show up.
Any tips on how to modify this javascript code? thanks.
<script type='text/javascript'>
var srcs = [];
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
}
var content = document.getElementById('content');
var images = content.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
srcs[i] = images[i].src;
loadImage(images[i], srcs[i],
function (cur, img, cached) {
cur.src = img.src;},
function (cur, img) {
cur.style.display = 'none';});
}
};
var loadImage = function (cur, url, callback, onerror) {
var img = new Image();
img.src = url;
img.width = '100%';
if (img.complete) {
callback && callback(cur, img, true);
return;
}
img.onload = function () {
callback && callback(cur, img, true);
return;
};
if (typeof onerror == 'function') {
img.onerror = function () {
onerror && onerror(cur, img);
}
}
};
</script>
The source code of the page is :
<body onload="doBindLinks();"><div id="content"> images and text </div></body>
P.S: Because I need to write this javascript string in C#, I replace the (") into (').
Edited:
Is the following right:
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
elem.setAttribute('display','none');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
elem.attachEvent('onload',onImageLoaded);
}
};
window.onImageLoaded = function() {
var elem = event.srcElement;
if ( elem != null ) {
elem.setAttribute('display','block');
}
return false;
};
Besides, the css code is:
img {width: 100%; border-style:none;text-align:center;}
But the images still wouldn't show until all are loaded.
I'm not 100% sure I understand your question. Are you trying to hide the image until it is fully loaded? Are you writing the images out to the page, or are they already in the page? Here are a couple of options:
set style="display:none". Then add onload="this.style.display='';" event listener to image.
images will each show as they are loaded.
if you are able to change the c# code, then simply write all the image urls out as a list of strings into an imageload function. Then use this function to create the images and add them to the content div.
I hope this helps you. If not, please provide more context, and I will try to help farther.
Ok, I see where you are going now. You can take out all that javascript that you have written. Maybe print it out so that you can throw it in the trash. Then take my example here... and it will do the trick for you. each image shown only as it is loaded. Obviously if you want to change any other properties you can do it in the showImage function. hope this helps.
<html>
<head>
<style>
img{display:none;}
</style>
<script type="text/javascript">
function showImage(elem) {
elem.style.display = 'block';
}
</script>
</head>
<body><div id="content">
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
</dvi>
</body>
</html>

Javascript fadein on mouseover works but doesn't fadeout

So real simply, I have figured out how to fade a div in on a mouseover call. But I want to know how to fade it out without simply duplicating the javascript opposite of what it already is and linking that to a onmouseout.
Here is my Javascript:
<script type="text/javascript">
function fadein(objectID){
object = document.getElementById(objectID);
object.style.opacity = '0';
animatefadein = function (){
if(object.style.opacity < 1){
var current = Number(object.style.opacity);
var newopac = current + 0.1;
object.style.opacity = String(newopac);
setTimeout('animatefadein()', 100);
}
}
animatefadein();
}
and my html
<div id="rolloverwrapper" style="opacity:0;"></div>
<div id="wrapper">
<div id="content">
<div id="button">
<img src="images/dj.png" onmouseover="fadein('rolloverwrapper');"/>
</div>
</div>
</div>
Try something like this:
<script type="text/javascript">
function fade(objectID, amount) {
var MIN_OPACITY = 0;
var MAX_OPACITY = 1;
object = document.getElementById(objectID);
animatefade = function() {
if(object.style.opacity < MAX_OPACITY && object.style.opacity > MIN_OPACITY){
var current = Number(object.style.opacity);
var newopac = current + amount;
object.style.opacity = String(newopac);
setTimeout('animatefade()', 100);
}
}
animatefade();
}
</script>
With the following HTML:
<img src="images/dj.png" onmouseover="fade('rolloverwrapper', 0.1);" onmouseout="fade('rolloverwrapper', -0.1);"/>
If the behavior you want is the opposite of what you already have, but on a different event, then simply do it. Don't look for fancy solutions when you know a simple one already and it works.
Add a parameter to your fadein function to specify the fade direction. 1/-1, 0/1, t/f, etc... and pass that in to your animatefadein.
Then you'd have
<img src="..." onmouseover="fadein('rolloverwrapper', 1)" onmouseout="fadein('rolloverwrapper, 0)" />
However, you should look into using jquery for this sort thing. The library would be a "heavy" compared to just these few lines of JS, but the flexibility you gain is vast.

Categories

Resources