Javascript slideshow with caption issues - javascript

So I am having issues with captioning my slide show using a javascript, can somebody let me know as to where I am going wrong. My code stands as this:
JavaScript Document
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
var img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
if( img.attr("src") == "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.attr("src") == "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.attr("src") == "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.attr("src") == "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.attr("src") == "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
HTML document
<div class="slides">
<img id="img1" src="">
</div>
<input type="image" src="images/Next.png" id="button" onClick="javascript:moveToNextSlide()" title="Next" >
<div id ="captionbar"></div>
Also to note, that I get this error within the "inspect element":
Uncaught TypeError: Cannot call method 'attr' of null
REVISED
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
window.onload = function(){
if( img.src === "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.src === "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.src === "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.src === "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.src === "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
}
The HTML Remains the same as before.
No error references however function does not write the text whatsoever.

Replace all img.attr('src') by img.src=="your image name".
For example:
img.src=="movieImages/img1.jpg"
As you are using pure JavaScript,you cannot use attr() which is method of JQuery.

attr() is a method brought by JQuery. If you are not using JQuery, you should keep using img.src. Another thing I noticed that might cause trouble : when you read .src from your image, you get the full path as a return (including your domain).
Your conditions would then become :
img.src === "http://yourdomain.com/movieImages/img1.jpg"
( And I just checked to be sure : http://www.w3schools.com/jsref/prop_img_src.asp mentions that the return value of img.src includes protocol and domain )
Also I think you should either define your function CaptionSlide inside moveToNextSlide so that it gains access to the updated img variable or not declare your img variable inside the moveToNextSlide function (so that the global variable gets updated instead)
Another point : you should make sure the DOM is loaded before querying elements from it (such as img) . To do so, wrap your code in a function, and assign it to the window.onload event :
window.onload = function() {
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
...
}
function CaptionSlide()
{
if( ... )
...
}
document.getElementById("button").addEventListener('click', moveToNextSlide);
}
and HTML for button :
<input type="image" src="images/Next.png" id="button" title="Next" />

Related

How to set img src dynamically with a function

I want to set img src=" " with a function in javascript that changes the picture upon a variable and checks values:
javascript file code:
function myFunctionstatus(){
var ledactual=document.getElementById("ledonof").value
var image = document.getElementById('ledPic');
if (ledactual==ledon) {
image.src = "https://cdncontribute.geeksforgeeks.org/wp-c
content/uploads/OFFbulb.jpg";
}
if (ledactual==ledoff){
image.src = "https://cdncontribute.geeksforgeeks.org/wp-
content/uploads/ONbulb.jpg";
}
} };
img src in html file:
<img id="ledPic" [src]="myFunctionstatus()" >
but it didn't work with me and the picture didn't appear! the script is working, I tested with a button:
<input type="button" id="ledonof" onclick="myFunction();myFunctionstatus();" class="ledonoff" value="<?phpinclude ('ledstatus.php'); ?>">
how can I set img src with a function?
I can't comment on the php that you're using to get the status, but the below is a working javascript example:
function myFunctionstatus(){
var input = document.getElementById("ledonof");
var image = document.getElementById('ledPic');
if (input.value == "on") {
image.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/ONbulb.jpg";
input.value = "off"
} else if (input.value == "off"){
image.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg";
input.value = "on"
}
}
myFunctionstatus()
<img id="ledPic" />
<input type="button" id="ledonof" onclick="myFunctionstatus();" class="ledonoff" value="on">
As noted by others, src doesn't support function calls (and you don't even return anything from your function call), so you need to run the function once at the start to set the image to the initial status.
You need to set an initial state manually
function switchStatus() {
let switchButton = document.getElementById('ledonof');
let img = document.getElementById('ledPic');
if(switchButton.value == "ledon") {
img.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg";
switchButton.value = "ledoff";
} else {
img.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/ONbulb.jpg";
switchButton.value = "ledon";
}
}
<img id="ledPic" src="https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg" > <input type="button" id="ledonof" onclick="switchStatus();" value="ledoff">
img src attr does not support function call. Whatever you pass in the src will be considered as url(relative or otherwise).
Please refer https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#Attributes
So what you need to do is call the function before/loading your element and change the src then. The simplest form would be following
`<script>
(function() {
// your page initialization code here
// the DOM will be available here
// call the function here
})();
</script>`
You can't do this. The src attribute of an image element can't be interpreted as javascript when the HTML is interpreted.
initially, you need to set src, and on button click, you can toggle image by changing image src.

How to have two fallback image placeholders

This works really well for filling a placeholder in place of an image that doesn't exist.
<img src="cantfind.jpg" onError="this.onerror=null;this.src='http://placehold.it/600x600?text=No Picture'">
What I was curious about is if there was a way to do two placeholders within the onError event. So I tried doing this but the Javascript isn't coming to me. any ideas? I tried assigning the urls to variable, but I'm not sure how to check for if the first placeholder fails without doing some messy xhr request or something.
Check if the current src equals one of the placeholders and assign a new url accordingly:
onerror="
var p1='http://.......', p2='http://......';
if (this.src == p1) this.src = p2; else if (this.src != p2) this.src = p1;
"
Here's one way of doing it via recursive event handling... try loading and if it errors, then try loading the first element from the array, and set it to error with the next index on failure, until you hit an index that is out of range, at which point stop.
This caters for any number of defined placeholders in the sources array.
<img id="img" src="example.jpg" onerror="loadNextImage(0);" alt="logo image">
<script>
var imagesDir = 'path/to/images/directory/';
var sources = [ '01.jpg', 'test.gif', 'bamf.jpg', 'foobar.jpg' ];
var index = 0;
function loadNextImage(index) {
var image = document.getElementById('img');
if (index < sources.length) {
console.log('Index:', index, sources[index]);
image.onerror = function() { loadNextImage(index + 1); };
image.src = imagesDir + sources[index];
} else {
image.alt = 'No suitable image found to display';
}
}
</script>

How to assign Javascript Image object to existing Img element of JSP

JSP code is written as below,
< img src='<%=imageURL%>' id='advt-image-top' border='0' alt=''" /><br/>
Where the value of imageURL is like,
http://1.2.3.4:5678/ads/avw.php?zoneid=1234567890&cb=INSERT_RANDOM_NUMBER_HERE
(Sample URL which fetches random advertisement image from Ad-Server)
Now, same JSP page contains javascript-code like below:
$(document).ready(function() {
var imgAd = new Image();
imgAd.src = '<%=imageURL%>';
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
document.getElementById('advt-image-top').src='img/default_top.jpg';
}
}
}
Above javascript code checks - if image returned from ad-server is of size 1x1, then it should be replaced with default-image.
Problem is, above entire code-snippet executes "imageURL" twice in order to fetch one image from ad-server : one to check whether image-returned-from-ad-server is of size 1x1 and other during tag execution.
How can I optimize above code so that "imageURL" is executed only once?
How can I assign Image() object of javascript (after 1x1 validation is passed) to JSP's 'advt-image-top' element?
Thanks in advance.
You just need a minor adjustment to your javascript code, there is no need to create an Image:
$(document).ready(function() {
var imgAd = document.getElementById('advt-image-top');
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
}
However, the image might get loaded before the document ready fires and lose the onload event, so you might want to load the default url in your tag:
< img src='img/default_top.jpg' id='advt-image-top' border='0' alt=''" /><br/>
...and apply the remote url by code:
$(document).ready(function() {
var imgAd = document.getElementById('advt-image-top');
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
imgAd.src='<%=imageURL%>';
}
EDIT: probably the best way is to remove the img tag altogether from the jsp and write everything with javascript. Supposing that the image is contained in an element with id "container":
$(document).ready(function() {
var imgAd = new Image();
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
imgAd.src='<%=imageURL%>';
imgAd.id='adv-image-top';
imgAd.border=0;
document.getElementById('container').appendChild(imgAd);
}
#dipanda, Thanks for your comments. Helped me solve my problem.
var $imgObj = $("<img/>",{src:"<%=imageURL%>"});
$imgObj.load(function(){
var imgJS = $imgObj[0];
if(imgJS.height == 1 && imgJS.width == 1){
document.getElementById('advt-image-top').src='img/default_top.jpg';
}else{
if($("#advt-image-top")!=null && $("#advt-image-top")!=undefined){
$("container").append($imgObj);
}
}
};

Change button image onclick

I have this code to change from image 1 to image 2. How can I make it change from image 2 to image 3, and back to image 1? Thanks
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()"><img id="myImg" src="image1.gif" width="107" height="98"></button>
<script>
function myFunction()
{
document.getElementById("myImg").src="image2.gif";
}
</script>
</body>
</html>
http://jsfiddle.net/9R2J7/1/
var img_array = ['http://placehold.it/100x100/green', 'http://placehold.it/100x100/blue', 'http://placehold.it/100x100/red'];
i = 0;
function myFunction() {
i++;
document.getElementById("myImg").src = img_array[i];
if (i == img_array.length - 1) {
i = -1;
}
}
You could do
function myFunction()
{
if( document.getElementById("myImg").src == "image1.gif" ){
document.getElementById("myImg").src = "image2.gif";
}
elseif( document.getElementById("myImg").src == "image2.gif" ){
document.getElementById("myImg").src = "image3.gif";
}
else{
document.getElementById("myImg").src = "image1.gif";
}
}
It's not very elegant, but it could be a solution.
Kind regards.
Using jQuery.
change your html to something of the sort:
<button id="change-img"><img ... /></button>
Then you can add an onclick to the #change-img element. In your jQuery, add
$('#change-img').click(function() {
var image = $('#myImg');
var imgNum = image.attr('src').split('.')[0].replace('image', ''); // gets the number
imgNum = (imgNum % 3) + 1;
image.attr( { 'src' : 'image' + imgNum + '.gif' } ); // selects image, changes source
});
And there you have it.
Made a demo, similar to what you'd like to achieve: http://jsfiddle.net/94VKa/.
One further approach:
// initialise the array, using array-literal syntax:
var img_array = ['http://placehold.it/100x100/green',
'http://placehold.it/100x100/blue',
'http://placehold.it/100x100/red'];
function myFunction() {
// finding where in the 'img_array' the current src is to be found:
var current = img_array.indexOf(this.src);
// updating the src of the clicked element, to either the next element in
// the array (if 'current + 1' does *not* evaluate to equal the length of the
// array, or to the first element in the array if 'current + 1' *does* equal
// the length of the array:
this.src = img_array[current + 1 === img_array.length ? 0 : current + 1];
}
// getting a reference to the element to click on,
// add an event-listener to 'listen' for that event, and execute the
// named function:
document.getElementById('myImg').addEventListener('click', myFunction);
JS Fiddle demo.
References:
Array.prototype.indexOf().
Conditional ('ternary') operator.
document.getElementById().
EventTarget.addEventListener().

ie8 Member not found when setting style

This code works fine in firefox, when Search button clicked, an image pops inside the myText box, right aligned:
function showImg(){
var setStyle = document.getElementById('myText').style ==
"background-color:white" ?
document.getElementById('myText').style =
"background: url(/somePath/someImg.gif) no-repeat; background-position:right; background-color:white" :
document.getElementById('myText').style == "background-color:white";}
<input type="text" id="myText">
<input type="button" value="Search" onClick="showImg()">
but in IE8 throws "Member not found". it's definitely related to setting the style, but i can't figure how to get around it
thanks for any help
#
thanks everybody for answering. cssText works when trying to detect an existing style string, but not when trying to set it (won't throw an error, but no image either). If i try to use style= to set it, i get the Member not found error. That makes me think that trying to preload the image with visibility:hidden woudn't work either
function showImg(){
if (document.getElementById('myText').cssText = "background-color:white"){
alert("style detected"); // this works
document.getElementById('myText').cssText="background: url(/somePath/someImg.gif) no-repeat; background-position:right; background-color:white"; // this doesn't
} else { alert("style not detected"); }}
<input type="text" id="myText" style="background-color:white">
<input type="button" value="Search" onClick="showImg()">
#
i found kind of a solution, works as a toggle in IE8 (img appears/disappears onClick inside text box). However, in firefox, it appears/disappears only once (!) then does nothing. Would somebody know how to fix that?
i've created a second, invisible image (one pixel, transparent), and i'm switching them
picShow=new Image();
picShow.src="/somePath/realImage.gif";
picHide=new Image();
picHide.src="/somePath/invisibleImage.gif";
function showImg() {
var imgPath = new String();
imgPath = document.getElementById('myText').style.backgroundImage;
if (imgPath == "url(/somePath/invisibleImage.gif)" || imgPath == "") {
document.getElementById('myText').style.backgroundImage = "url(/somePath/realImage.gif)";
document.getElementById('myText').style.backgroundRepeat="no-repeat";
document.getElementById('myText').style.backgroundPosition="right";
} else {
document.getElementById('myText').style.backgroundImage = "url(/somePath/invisibleImage.gif)";
}
}
#
ahhh, firefox creates the backgroundImage putting the url within double quotes, like url("/somePath/invisibleImage.gif"), but IE doesn't. just have to escape them for firefox. this is the working code, just in case someone else needs it. Thanks again everybody!
picShow=new Image();
picShow.src="/somePath/realImage.gif";
picHide=new Image();
picHide.src="/somePath/invisibleImage.gif";
function showImg() {
var imgPath = new String();
imgPath = document.getElementById('myText').style.backgroundImage;
if (imgPath == "url(/somePath/invisibleImage.gif)" || imgPath == "url(\"/somePath/invisibleImage.gif\")" || imgPath == "") {
document.getElementById('myText').style.backgroundImage = "url(/somePath/realImage.gif)";
document.getElementById('myText').style.backgroundRepeat="no-repeat";
document.getElementById('myText').style.backgroundPosition="right";
} else {
document.getElementById('myText').style.backgroundImage = "url(/somePath/invisibleImage.gif)";
}
}
Where you have used .style use .cssText instead.
Example:
document.getElementById('myText').cssText == "background-color:white";
The problem is you can not set the style like that and using a ternary operator like that is a bad idea. You would need to use cssText.
var elem = document.getElementById('myText');
var style = (elem.cssText == "background-color:white" ? "background: url(/somePath/someImg.gif) no-repeat; background-position:right; background-color:white" :
"background-color:white";
elem.cssText = style;
A better solution is just setting a CSS class and have a rule in your stylesheet that corresponds.
var elem = document.getElementById('myText');
var className = (elem.className=="active") ? "" : "active";
elem.className = className;
and the CSS
#myText{
background-color: #FFFFFF;
}
#myText.active {
background: url(/somePath/someImg.gif) no-repeat;
background-position:right;
}
firefox creates the backgroundImage putting the url within double quotes, like
url("/somePath/invisibleImage.gif"), but IE8 doesn't. just have to escape them for firefox. this is the working code, just in case someone else needs it.
picShow=new Image();
picShow.src="/somePath/realImage.gif";
picHide=new Image();
picHide.src="/somePath/invisibleImage.gif";
function showImg() {
var imgPath = new String();
imgPath = document.getElementById('myText').style.backgroundImage;
if (imgPath == "url(/somePath/invisibleImage.gif)" || imgPath == "url(\"/somePath/invisibleImage.gif\")" || imgPath == "") {
document.getElementById('myText').style.backgroundImage = "url(/somePath/realImage.gif)";
document.getElementById('myText').style.backgroundRepeat="no-repeat";
document.getElementById('myText').style.backgroundPosition="right";
} else {
document.getElementById('myText').style.backgroundImage = "url(/somePath/invisibleImage.gif)";
}
<input type="text" id="myText">
<input type="button" value="Search" onClick="showImg()">

Categories

Resources