I'm trying to make a simple slideshow with JavaScript.
Here is my index.html
<body>
<h1>Slideshow example</h1>
<button onclick="slideshow.timer()">Next slide</button>
<div id="container"></div>
<script src="slide.js"></script>
</body>
And here is slide.js
var slideshow = {
sliderImages: ["img/img1.png", "img/img2.png"],
timer: function() {
this.sliderImages.forEach(function(img) {
var container = document.getElementById('container');
var image = document.createElement('img');
container.appendChild(image);
image.src= img;
})
}
}
If I click the "next slide" button, I see both of the images. It loops through the whole array. How could I make it loop through the array just once, when clicking the button?
I tried adding container.innerHTML = ''; so that the previous image would be removed when adding the next image, but that resulted it showing immidietly the image in sliderImages[1]. Am I approaching this whole thing wrong?
I updated your code. It is not the best way to write it but I just modified your example to show you the problem. The problem is your timer function which is just going through all the elements in the array at once. Instead what you may want to do is add some delay.
var slideshow = {
sliderImages: ["img/img1.png", "img/img2.png"],
currentImgIndex: 0,
timer: function() {
if (this.currentImgIndex < this.sliderImages.length ) {
var image = document.getElementById('img');
image.src= this.sliderImages[this.currentImgIndex];
this.currentImgIndex++;
setTimeout(function (){ slideshow.timer()}, 2000)
} else {
alert("no more images");
}
}
}
<body>
<h1>Slideshow example</h1>
<img id="img"/>
<button onclick="slideshow.timer()">Next slide</button>
<div id="container"></div>
<script src="slide.js"> </script>
</body>
If you are going to change the images only when the button is clicked, you don't need the forEach loop. If you are going to change images without user interaction then you need the loop but you need setInterval also.
Related
Why doesn't the second (hawk) image appear when the button is clicked? It goes straight to the else statement showing the ant image.
<!DOCTYPE html>
<html>
<body>
<script>
function changeImg() {
if (document.getElementById("cycle").src == "fox.jpg") {
document.getElementById("cycle").src = "hawk.jpg";
} else {
document.getElementById("cycle").src = "ant.jpg";
}
}
</script>
<button onclick = "changeImg()">change image</button>
<img id ="cycle" src ="fox.jpg"/>
</body>
</html>
Please add your script tags at the end of the body to make sure that your dom is rendered before accessing any elements. (like in my example)
The problem with your code is, that you need to add a new if for every new image you add. As you noticed yourself, it becomes hard to understand and debug.
For something like cycling, use an array and modulo operation on the index of that array.
With this solution, you can add as many images to the images array as you like, without touching the code/logic;
<!DOCTYPE html>
<html>
<body>
<button onclick="changeImg()">change image</button>
<img id="cycle" />
<script>
var imageElement = document.getElementById("cycle");
var images = ["fox.jpg", "hawk.jpg", "ant.jpg"]; // add as many images as you want
var counter = 0;
imageElement.src = images[counter] // set the initial image
function changeImg() {
counter = (counter + 1) % images.length;
imageElement.src = images[counter];
}
</script>
</body>
</html>
document.getElementById("cycle").src always has full url of image (example:https://example.loc/example/fox.jpg) and this is not similar from fox.jpg.
You need try another solution.Try use
cycle.getAttribute('src')
Example code:
function changeImg() {
let cycle = document.getElementById("cycle");
console.log(cycle.src,cycle.getAttribute('src')); // show real value and taribute
if (cycle.getAttribute('src') == "fox.jpg") {
cycle.src = "hawk.jpg";
} else {cycle.src = "ant.jpg";
}
}
Use getAttribute('src') if you want to access the actual contents of the attribute. Otherwise you get the resolved URL.
var cycle = document.getElementById("cycle");
if (cycle.getAttribute('src') == "fox.jpg") {
cycle.src = "hawk.jpg";
} else {
cycle.src = "ant.jpg";
}
I have a newsfeed in my CMS that pulls preview images as well as teaser text for the feed. The images are all thumbnails # 75x75px. I wanted to have the preview images much larger, but cannot scale an image that small.
I'm wondering what JS I need to run to replace all the URL's to the original image src.
Have:
Need to change them all to the below - which is just replacing 'thumb' with 'large':
This needs to apply to a whole css class; as it is a newsfeed & there will be new articles
Here's where I'm at:
function replaceImgSrc(img,imgTwo) {
var arr=[img,imgTwo];
for(i=0;i<arr.length;i++)
arr[i].each(
function(i,e) {
theImg=$(this),
theImg.attr("src",
function(i,e) {
return e.replace("_thumb","_large")
}
)
}
)
}
If the newsfeed is wrapped in a class, try this way.
function replaceImg($class) {
$class.find("img").each(function(k, el) {
var newSrc = $(el).attr("src").replace("_thumb", "_large");
$(el).attr("src", newSrc);
});
}
replaceImg($("#newsfeed"));
And in your HTML, wrap the newsfeed code inside an identifiable DIV.
<div id="newsfeed"> {{place newsfeed code in here}} </div>
Try this fiddle jsfiddle.net/bharatsing/wkh6da93/
This will find all images in page and change its src with large image.
$(document).ready(function(){
$("#btnLarge").click(function(){
$("img").each(function(){
var src=$(this).attr("src");
src=src.replace("_thumb","_large");
var src=$(this).attr("src",src);
});
});
});
If the assumption is that you have all img elements in an array var imgArray, then you can iterate thru them and update the src attribute like this:
imgArray.forEach(enlargeImageSrc);
function enlargeImageSrc (image) {
image.src = image.src.replace('_thumb', '_large');
}
Try this hovering over the button will make the images with class="show" bigger, as soon as you remove the mouse they are small again.
$("button").mouseenter(function (){
var srcI = $(".show").attr("src");
srcI = srcI.replace("thumb","large");
$(".show").attr("src",srcI);
});
$("button").mouseleave(function (){
var srcI = $(".show").attr("src");
srcI = srcI.replace("large","thumb");
$(".show").attr("src",srcI);
});
button{
display:block;
}
img.show{
max-width:400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button>Click me</button>
<img class="show" src="http://cdn4.sportngin.com/attachments/news_article/7560/0742/Screen_Shot_2017-01-04_at_11.30.31_AM_thumb.png"/>
</div>
I make a code for you where I take two variables one for large image URL and one for small image URL. I create a function on click on change image button your image url change to big image and it show you big image and then you again click on that button it change big image to small image. You can also see the live demo of this here https://jsfiddle.net/Arsh_kalsi01/3s1uudhe/2/
$(document).ready(function(){
var big_image = "http://cdn4.sportngin.com/attachments/news_article/7560/0742/Screen_Shot_2017-01-04_at_11.30.31_AM_large.png";
var small_image = "http://cdn4.sportngin.com/attachments/news_article/7560/0742/Screen_Shot_2017-01-04_at_11.30.31_AM_thumb.png";
$(document).on("click",".Changeimagetolarge",function(){
var obj = $(this);
obj.removeClass('Changeimagetolarge');
obj.addClass('Changeimagetosmall');
obj.next("img").attr('src',big_image);
});
$(document).on("click",".Changeimagetosmall",function(){
var obj2 = $(this);
obj2.removeClass('Changeimagetosmall');
obj2.addClass('Changeimagetolarge');
obj2.next("img").attr('src',small_image);
});
});
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<div>
<button class="Changeimagetolarge">
Change Image
</button>
<img src="http://cdn4.sportngin.com/attachments/news_article/7560/0742/Screen_Shot_2017-01-04_at_11.30.31_AM_thumb.png">
</div>
I have a code where onclick a word on left side of the page, it shows some text on right hand side of page. Here's the jsfiddle of working code.
Now, my problem is I want to display spinning circle on page on every onclick and then show text on the right hand side of the page. My code for spinning circle is:
HTML:
<div id="loading">
<img src="http://jimpunk.net/Loading/wp-content/uploads/loading1.gif"/>
</div>
JavaScript:
function hideLoading() {
document.getElementById("loading").style.display = 'block';
}
function showLoading() {
document.getElementById("loading").style.visibility = 'visible';
}
CSS:
#loading {
display: none;
}
Now, I don't know how to place them in my working code to get the desired result. Anybody knows the correct way of doing it?
Desired result: onclick "abc" on left hand side, spinning circle should be displayed for 1 sec and then "I should be printed on left side" should be displayed. Again on clicking "mno", first spinning circle should be shown for 1 sec and then text "I should be printed on left side" will be displayed. The fiddle has working version of onclick.
You should use a single handler function on each element that will both hide and show the loading gif. Also, it's a good idea not to use getElementById on every call, so save it in a variable:
<div id="container">
<div id="header">
<h1>Main Title of Web Page</h1>
Here I am trying to split the webpage into two columns and display text.</div>
<div id="one">
<div id="loading">
<img src="http://support.snapfish.com/euf/assets/images/answer_images/SpinningWheel.gif" />
</div>
<div id="message"></div>
</div>
<div id="two"> <b>This is test one<br /></b>
<b>This is test two<br /></b>
</div>
Javascript:
var elements = {};
function loadSpanContent() {
elements.loading.style.display = 'block'; // Show loading gif
spanContent = this.innerHTML
setTimeout(function () {
elements.message.innerHTML = "I should be printed on left side - " + spanContent;
elements.loading.style.display = 'none'; // Hide loading gif
alert("onclick Event detected! " + spanContent);
}, 1000);
}
window.onload = function mydisplayArray() {
var array = ['abc', 'xyz', 'mno'];
elements.loading = document.getElementById("loading");
elements.one = document.getElementById("one");
elements.message = document.getElementById("message");
for (i = 0; i < array.length; i++) {
var span = document.createElement('span');
span.innerHTML = array[i];
span.onclick = loadSpanContent;
one.appendChild(span);
}
};
Here is a fiddle: http://jsfiddle.net/nBaCJ/1/
I'm still confused by what you actually want here, but if you want to have the loading message disappear after one second, you should use setTimeout. Something like this:
function showAlert() {
showLoading();
setTimeout(hideLoading,1000);
//Hide loading circle
var myString = "I should be printed on left side";
document.getElementById("two").innerHTML = myString;
}
But you also need to fix your "showLoading" and "hideLoading". Something like this:
function hideLoading() {
document.getElementById("loading").style.display = 'none';
}
function showLoading() {
document.getElementById("loading").style.display = 'block';
}
http://jsfiddle.net/7uxHC/9/
BTW: if you want your loading gif to appear over your content, then set its position:absolute in css, but note that you gif has a white, rather than transparent background so it will obscure your content.
Your request isn't clear.
But first, you should fix these 2 functions:
function hideLoading() {
document.getElementById("loading").style.display = 'none';
}
function showLoading() {
document.getElementById("loading").style.display = 'block';
}
i have this code and would like to have an animated gif to disappear after 3 seconds. i learned that i need to add window.onload=loadingGif(); to ensure the 'loadingGif' function is fired when the page loads. i stll have the problem that this code is not working how it should do. i would like to know what is going wrong with that? thanks.
i´m sorry i posted the wrong code. it must be:
<body>
<script type="text/javascript">
var counter = 3;
function downcount() {
document.getElementById('digit').firstChild.nodeValue = counter ;
if (counter == 0 ) {
document.getElementById('loading').style.display = 'none';
document.getElementById('msg').style.display = 'block';
} else {
counter--;
window.setTimeout('downcount()', 1000);
}
}
window.onload=downcount;
</script>
<div id="loading">
<img src="loading/loading40.gif"/>
</div>
<div id="msg" style="display:none">
<?PHP echo $_SESSION['msg'];?>
</div>
Close the img tag.
Also, where's digit? If that doesn't exist then you'll be getting JS errors.
You're doing three 1s setTimeout to wait for 3 seconds? Here is a simpler solution, right out of my head...
window.onload = setTimeout(removeImg, 3000)
var removeImg = function() {
document.getElementById('loading').style.display = 'none'
document.getElementById('msg').style.display = 'block'
}
I'm pretty new to javascript and programming and have run into a brick wall with my project. I have a div which contains the javascript to embed a quicktime player, when the page is first loaded no .mov file is pointed at by the page so a placeholder div is 'unhidden' and the player div is set to style.display = 'none'.
So far so good, the user then enters the name of the new movie, the placeholder div is hidden and the player div is unhidden. My problem is that the javascript in the player div didn't run when the div was made visible, if I make the script for the player into a seperate function then call it when the player div is unhidden then the player runs full screen and not in the div.
I've tried using jquery to add the javascript into the div after the div is made visible but can't seem to get $("#player").load(somescript) or $("#player").html(htmlwithjavain) to add the script.
I know the player div contenst can be changed as I can use $("#player").empty(); and $("#player").html(); to manipulate it.
Thanks for reading, hope you can help
Here's the relevant code:-
<html>
<head>
<title>Browse Media Player</title>
<link rel="stylesheet" type="text/css" href="CSS/browser.css" />
<script type="text/javascript">
<!--
var userinterrupt=false;
var runonce=false;
var currentfile;
var basemediapath = "http://10.255.10.71/IsilonBrowse/movfiles/";
var playerheight = 750;
var playerwidth = 900;
var currenttc;
var basetime;
var baseduration;
var currentduration = "no tc available";
var tcoffset = 35990;
var playspeed = 1;
var boolisplaying=true;
var boolonslide=false;
//function to fire off other methods when the DOM is loaded
//Use in place of body onload, using jquery library
//
$(document).ready(function()
{
//showEvents('jquery running');
showhideplayer(null);
});
//-->
</script>
</head>
<body onload="forceslider(); timecode()">
<div class="container">
<div id="timecode_container">
<div class="tc_overlay"></div>
<div id="timecode" class="timecode"></div>
</div>
<div id="player" class="playerdiv" style="display:none;">
**javascript for player goes here...**
</div>
<div id="noclipoverlay" class="playerdiv" style="display:none;">
<p>No media loaded...
</div>
<div id="noclipoverlay2" class="playerdiv" style="display:none;">
<p>loading media....
</div>
</div>
<div id="loadstatus"></div>
<div id="alerts"></div>
</body>
</html>
Now the mainstuff.js file which should add the javascript code:-
//function to switch the player div and mask div is no media file is
//defined in the 'currentfile' variable
//
function showhideplayer(state)
{
if (!currentfile)
{
showEvents('wtf no media');
document.getElementById("player").style.display = 'none';
document.getElementById("noclipoverlay").style.display = 'block';
}
else if (currentfile)
{
document.getElementById("player").style.display = 'block';
document.getElementById("noclipoverlay").style.display = 'none';
showEvents('valid media file');
}
}
//end of showhideplayer
//function to change movie files, note SetResetPropertiesOnReload must be set to false
//otherwise the B'stard player will default all attributes when setURL runs
//
function changemovie(newmovie)
{
oldfile = currentfile;
if (newmovie == currentfile)
{
showEvents('same file requested so no action taken');
return;
}
if (newmovie != currentfile)
{
showEvents('changing movie');
//switch the divs around to hide the 'no media slide'
document.getElementById("player").style.display = 'block';
document.getElementById("noclipoverlay").style.display = 'none';
}
showEvents('movie changed to: '+newmovie);
currentfile=newmovie;
if (!oldfile)
{
$("#player").empty();
showEvents('the old media file was blank');
$("#player").load("/path/loadplayer.js");
}
document.movie1.Stop();
document.movie1.SetResetPropertiesOnReload(false);
document.movie1.SetURL(currentfile);
//showEvents('movie changed to: '+newmovie);
if (boolisplaying)
{
document.movie1.Play();
}
}
[EDIT] and here's the contents of loadplayer.js:-
var movie1 = QT_WriteOBJECT(
currentfile, playerwidth, playerheight, "",
"controller","false",
"obj#id", "movie1",
"emb#id","qt_movie1",
"postdomevents","True",
"emb#NAME","movie1",
"enablejavascript","true",
"autoplay","true",
"scale","aspect",
"pluginspage","http://www.apple.com/quicktime/download/"
);
Without knowing the content of your loadplayer.js file, it will be difficult to give you a solution.
For example, if the script attempts to do a document.write() after the page has loaded, it will create a new page, overwriting the current page. Is that what you mean when you say the quicktime movie is running full screen?
Also it is generally not a good idea to load a SCRIPT element and insert it as HTML. When you add HTML to the page, jQuery finds all the SCRIPT elements and evaluates them in a global context, which might give you unexpected results.
Use QT_GenerateOBJECTText_XHTML or QT_GenerateOBJECTText from AC_QuickTime.js if you'd like to return a string.