By clicking on the button , the random two pictures should appear of 12 included in two boxes.But something goes wrong.Need advice to solve this this problem.
var startBtn = document.getElementById("start-button");
var imgBox1 = document.getElementById("firstBox");
var imgBox2 = document.getElementById("secondBox");
var images = [
'/assets/img/pic1.png',
'/assets/img/pic2.png',
'/assets/img/pic3.png',
'/assets/img/pic4.png',
'/assets/img/pic5.png',
'/assets/img/pic6.png',
'/assets/img/pic7.png',
'/assets/img/pic8.png',
'/assets/img/pic9.png',
'/assets/img/pic10.png',
'/assets/img/pic11.png',
'/assets/img/pic12.png',
];
function loadImages(imgArr){
for(var i=0; i< imgArr.length; i++) {
console.log(imgArr[i]);
var img = new Image();
img.src = imgArr[i];
document.getElementById('output').appendChild(img);
}
}
startBtn.onclick = function(){
imgBox1.style.backgroundImage = images[Math.floor(Math.random()*images.length)];
imgBox2.style.backgroundImage = images[Math.floor(Math.random()*images.length)];
}
You need to use CSS's url function when setting the background image:
startBtn.addEventListener("click", function() {
imgBox1.style.backgroundImage = `url('${images[Math.floor(Math.random() * images.length)]}')`
imgBox2.style.backgroundImage = `url('${images[Math.floor(Math.random() * images.length)]}')`
});
You didn't add a button with id start-button by which you want to click. Essentially you are clicking on nothing.
<button type="button" id="start-button" style="">Start</button>
Related
I'm really new to javascript from C# and i'm having a little trouble. I wrote this function to make adding menu's a bit easier on my site. It works well except I can't seem to give my div's an individual url, even though I can give them an individual innerHtml.
I've been stuck trying different things such as divs[i].location.url etc.. but I can't seem to have anything work. My current solution has each div link to /contact.html which I'm a little confused by.
function DrawMainMenu() {
var btns = [
["About", "/about.html"],
["Portfolio", "/portfolio.html"],
["Resume", "/resume.html"],
["Contact", "/contact.html"]
];
var numOfBtns = btns.length;
var divs = new Array(numOfBtns);
for (var i = 0; i < numOfBtns; i++) {
divs[i] = document.createElement("div");
divs[i].className = "menuBtn";
divs[i].innerHTML = btns[i][0];
divs[i].style.height = (30 / numOfBtns) + "%";
divs[i].style.lineHeight = 3.5;
var link = btns[i][1];
divs[i].addEventListener('click', function() {
location.href = link;
}, false);
document.getElementById("buttons").appendChild(divs[i]);
}
}
Thanks
The problem is that the variable link gets overwritten each iteration, so when the event handler it gets link, which is the string '/contact.html', since that was the last value given to it.
You can try setting onclick attribute to elements, which will store the variable in the attribute onclick. Therefore, it will have the old and correct value.
function DrawMainMenu() {
var btns = [
["About", "/about.html"],
["Portfolio", "/portfolio.html"],
["Resume", "/resume.html"],
["Contact", "/contact.html"]
];
var numOfBtns = btns.length;
var divs = new Array(numOfBtns);
for (var i = 0; i < numOfBtns; i++) {
divs[i] = document.createElement("div");
divs[i].className = "menuBtn";
divs[i].innerHTML = btns[i][0];
divs[i].style.height = (30 / numOfBtns) + "%";
divs[i].style.lineHeight = 3.5;
var link = btns[i][1];
divs[i].setAttribute('onclick', 'location.href = "' + link + '"');
document.getElementById("buttons").appendChild(divs[i]);
}
}
DrawMainMenu();
<div id="buttons"><div>
Updated answer
Here we make use of closures. Using a closure (closing the values of link) we bind the value to the scope of the click handler.
function DrawMainMenu() {
var btns = [
["About", "/about.html"],
["Portfolio", "/portfolio.html"],
["Resume", "/resume.html"],
["Contact", "/contact.html"]
];
var numOfBtns = btns.length;
var divs = new Array(numOfBtns);
for (var i = 0; i < numOfBtns; i++) {
(function() {
divs[i] = document.createElement("div");
divs[i].className = "menuBtn";
divs[i].innerHTML = btns[i][0];
divs[i].style.height = (30 / numOfBtns) + "%";
divs[i].style.lineHeight = 3.5;
var link = btns[i][1];
document.getElementById("buttons").appendChild(divs[i]);
divs[i].addEventListener('click', function() {
location.href = link;
}, false);
}());
}
}
DrawMainMenu();
<div id="buttons"><div>
Js beginner here.
I have a function like this:
generateSteps: function() {
var stepsLength = this.data.steps.length;
var dataStepsInit = this.data.steps;
for (var i = 0; i < stepsLength; i++) {
var stepsItem = dataStepsInit[i].ITEM;
var arrayItem = this.animationNodes[stepsItem - 1];
var transition = this.animationParameters[i].transition;
var options = this.animationParameters[i].options;
var speed = this.animationParameters[i].speed;
var delay = this.animationParameters[i].delay;
arrayItem.delay(delay).show(transition, options, speed);
if (dataStepsInit[i].AUDIOID) {
var audioClass = dataStepsInit[i].AUDIOID;
var audioPlayer = this.template.find("audio." + audioClass);
setTimeout(playAudioOnDelay,delay);
};
var playAudioOnDelay = function() {
audioPlayer[0].pause();
audioPlayer[0].currentTime = 0;
audioPlayer[0].play();
};
}
}
What it does is generate data from JSON and display animated elements one by one on delay. Animation part work fine. I can assign required animations and delay to DOM elements and show them in right order.
But what I want to do in the same time is also to play an audio on delay (so I use setTimeout). Everything is almost fine, I play audio in right time (correct delay value) but I always play the same audio (which is last element) because audioPlayer always is the same DOM node.
I think this have something to do with this or I mixed a scope?
Try this:
generateSteps: function() {
var stepsLength = this.data.steps.length;
var dataStepsInit = this.data.steps;
for (var i = 0; i < stepsLength; i++) {
var stepsItem = dataStepsInit[i].ITEM;
var arrayItem = this.animationNodes[stepsItem - 1];
var transition = this.animationParameters[i].transition;
var options = this.animationParameters[i].options;
var speed = this.animationParameters[i].speed;
var delay = this.animationParameters[i].delay;
arrayItem.delay(delay).show(transition, options, speed);
if (dataStepsInit[i].AUDIOID) {
var audioClass = dataStepsInit[i].AUDIOID;
var audioPlayer = this.template.find("audio." + audioClass);
setTimeout(playAudioOnDelay(audioPlayer),delay);
};
}
function playAudioOnDelay(audioPlayer){
return function(){
audioPlayer[0].pause();
audioPlayer[0].currentTime = 0;
audioPlayer[0].play();
}
}
}
Essentially, your problem looks like this: http://jsfiddle.net/po0rLnwo/
The solution is : http://jsfiddle.net/gpfuo1s8/
Check the console in your browser.
I'm trying to make an image cycle through a set of images, when you click a button. Why won't it work? I want to make sure the images are preloaded, so that it will not make the website slower.
var ImageSet = new Array();
ImageSet[0] = ImageOne;
ImageOne = newImage();
ImageSet[0].src = 'Website/Images/CoverPhotos/LogoCover.jpg';
ImageSet[1] = ImageTwo;
ImageTwo = newImage();
ImageSet[1].src = 'http://p1.pichost.me/i/64/1886374.jpg';
ImageSet[2] = ImageThree;
ImageThree = newImage();
ImageSet[2].src = 'http://abduzeedo.com/files/originals/5/50cuteanimpic6.jpg';
ImageSet[3] = ImageFour;
ImageFour = newImage();
ImageSet[3].src = 'http://www.onsecrethunt.com/wallpaper/wp-content/uploads/2015/01/Cool-Wallpapers-Card-Pictures-1200x675.jpg';
var ImageSwitchNo = 0;
function Change() {
if (ImageSwitchNo < 3) {
ImageSwitchNo++;
}else {
ImageSwitchNo = 0;
}
var ImageSrc = document.getElementById('HeaderPhotoImage').innerHTML;
ImageSrc.src = ImageSet[3];
}
You are giving ImageOne a value on line three after trying to store it in the array on the line before it.
Instead of this:
var ImageSet = new Array();
ImageSet[0] = ImageOne;
ImageOne = newImage();
ImageSet[0].src = 'Website/Images/CoverPhotos/LogoCover.jpg';
try doing it like this for all of them:
var ImageSet = [];
ImageOne = newImage(); //gives ImageOne a value.
ImageSet[0] = ImageOne; //THEN sets the index of ImageSet to that value.
ImageSet[0].src = 'Website/Images/CoverPhotos/LogoCover.jpg';
Your code may work if you change the second line from bottom,
ImageSrc.src = ImageSet[3];
to
ImageSrc.src = ImageSet[ImageSwitchNo];
This question may be a bit long winded but bear with me.
I am trying to update and array every time a user hits the save button.
When they click save an image of a canvas on the page is created.
These DataURI values are kept in an array.
Once the value is saved a thumbnail of sorts is created and added at the bottom of the screen.
Clicking the X icon on those images calls a function to remove the correct image from the array.
The images should then be redrawn with the update array values, thus removing it from the
screen.
I have included images to try and demonstrate:
Image #1 (when save is clicked and image added below):
http://postimg.org/image/cybazwydf/
Image #2 (after closing the on screen images, adding a new image adds the deleted ones again along with the new one):
http://postimg.org/image/gi5pcornl/
That is the issue, that it re-adds the deleted values.
I will post the code for it below:
function getDataUrl () {
var a = document.getElementById("theCanvas");
var context = a.getContext("2d");
var dataURL = a.toDataURL();
save(dataURL);
}
var theImages = new Array();
//Add dataURL to array:
function save(URL) {
theImages.push(URL);
var x = JSON.stringify(theImages);
localStorage.setItem('images', x);
drawImages(x);
}
function drawImages(array){
var array = localStorage.getItem("images");
array = JSON.parse(array);
//If an image is saved, display the saveArea div:
if (array.length > 0){
document.getElementById("saveArea").style.visibility="visible";
}
//Clear the elements that might already be in the div so they don't appear twice:
var theDiv = document.getElementById("saveArea");
while (theDiv.firstChild) {
theDiv.removeChild(theDiv.firstChild);
}
for (var x=0; x < array.length; x++){
//Create image for each value in array:
var divimg = document.createElement("div");
divimg.style.marginRight="10px";
//divimg.style.border = "1px dotted red";
divimg.className = "saveContainer";
divimg.style.width = 300+"px";
divimg.style.padding = 5+"px";
divimg.style.marginRight="10px";
divimg.style.height = 150+"px";
divimg.style.display="inline-block";
divimg.style.marginRight="35px";
document.getElementById("saveArea").appendChild(divimg);
var img = document.createElement("img");
img.src = array[x];
img.width = 300;
img.height = 150;
img.setAttribute("id", "theImageId");
img.style.marginRight="10px";
img.className = "saveImg";
//Add each image to the containing div:
divimg.appendChild(img);
//Create close button:
var close = document.createElement("img");
close.src="close.png";
close.width = 50;
close.height = 50;
close.border = 0;
close.style.position="relative";
close.style.bottom=115+"px";
close.style.right=40+"px";
close.className="closeButton";
//close.style.cssFloat="right";
//close.style.right= 0+"px";
var link = document.createElement("a");
link.href = "#";
link.appendChild(close);
link.nameIndex = x;
//WHEN THE USER CLICKS THE CLOSE ICON:
link.onclick = (function (x) {
var imageNum = this.nameIndex;
alert("You clicked to close image "+(imageNum+1));
//Remove the image:
array.splice(x,1);
alert("The length of this array is: "+array.length);
//Update localStorage:
localStorage.removeItem('images');
array = JSON.stringify(array);
localStorage.setItem('images', array);
drawImages(array);
} );
//Add the close button the the containing div:
divimg.appendChild(link);
//divimg.appendChild(close);
} //End Loop
} //End drawImages();
I've been trying to solve this for hours but no luck..
After removing the image from the array you are not storing it anywhere so the splice result is lost and the array remains the same
array.splice(x,1);
needs to be
array = array.splice(x,1);
I have created a "prev/next" slideshow using javascript, now I want to add a counter(1/10, 2/10, 3/10...) beside my "prev/next" buttons but nothing seemed to work.
This is my first time attempting to make a website, I know nothing about jQuery, so please stick with html+javascript if possible. Here is my script
var image = new Array(
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg",
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg")
var imgNumber=1
var numberOfImg=2
function previousImage(){
if(imgNumber>1){
imgNumber--
}
else{
imgNumber = numberOfImg
}
document.slideImage.src = image[imgNumber-1]
}
function nextImage(){
if(imgNumber < numberOfImg){
imgNumber++
}
else{
imgNumber = 1
}
document.slideImage.src = image[imgNumber-1]
}
if(document.images){
var image1 = new Image()
image1.src = "http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg"
var image2 = new Image()
image2.src = "http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg"
}
Script+html: http://jsfiddle.net/nLHY9/5/
(Prev/Next buttons seem not to be working on this----they work fine when I launched them from laptop to browser.)
you could have used some existing javascript image sliders, for example, sliderman slider, for your current code, you can do like, add an element like span, to hold the count, and you could add a function like:
function changeCounter(cur, total) {
document.getElementById("counter").innerHTML = cur + "/" + total;
}
and call it in your previousImage() and nextImage() functions, as in this demo jsfiddle
There are many pure css slideshows that are beautiful and can do impressive things. However, as you try to support older browsers, the pure css slideshows get less and less impressive or even impossible. JavaScript is the most flexible and powerful way to go. That being, I wanted to help you clean up your code. I only had a few minutes, so this is a quickly thrown together plugin, but it should get you on the right track.
First, a few notes on your code:
//you're missing semicolons everywhere. ";"
/* "var image" is very unclear.
* it's an array, so it should be plural "images"
* there aren't images in this array - it's image urls or sources
* instead of "new Array" you could just use "[]"
*/
var image = new Array(
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg",
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg")
var imgNumber=1 //the name doesn't mean anything. I have to assume that you mean "currentImgNumber" or something to that effect
var numberOfImg=2 //this could be determined by checking the length of your array - myArray.length
And here's my exampe plugin:
Live demo here (click).
/***** This section is how you use the plugin. I start writing with the usage and then I make it mean something *****/
window.onload = function() { //when the page is loaded
var fooElem = document.getElementById('foo'); //get an element where we will attach the plugin
var foo = Object.create(slideshow); //create a new slideshow object
foo.create({ //create a slideshow with the given options
element: fooElem, //the element where the slideshow will be
sources: [ //image urls
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg",
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg"
]
});
//we can make more of these and with different options
var barElem = document.getElementById('bar');
var bar = Object.create(slideshow);
bar.create({
element: barElem,
sources: [
"http://eggboss.com/wp-content/uploads/2013/09/The-Gentleman-233x300.png",
"http://fc07.deviantart.net/fs71/f/2013/040/8/a/profile_picture_by_classy_like_a_sir-d5uf426.jpg"
]
});
};
/**** now let's create the plugin and make it work as it is used above *****/
var slideshow = {
currentIndex: 0,
imgs: [],
create: function(options) {
options.element.className+= ' slideshow'; //add a class to the main element for styling
this.imgs = this.getImgs(options.sources); //make img html
var controls = this.getControls(); //make controls
//add the html to the element from the options
var frag = document.createDocumentFragment();
this.imgs.forEach(function(img) {
frag.appendChild(img);
});
frag.appendChild(controls);
options.element.appendChild(frag);
},
getImgs: function(sources) {
var imgs = [];
sources.forEach(function(src, i) {
var img = document.createElement('img');
img.src = src;
imgs.push(img);
if (i > 0) {
img.style.display = 'none'; //hide all but first image
}
});
return imgs;
},
getControls: function() {
var that = this; //so that we can access "this" within the click functions
var controls = document.createElement('div');
controls.className = 'controls';
var counter = document.createElement('span');
counter.className = 'counter';
this.setCounter(counter);
var prev = document.createElement('a');
prev.textContent = 'Prev';
prev.className = 'prev';
prev.addEventListener('click', function() {
newIndex = (that.currentIndex) ? that.currentIndex-1 : that.imgs.length-1;
that.changeImg(newIndex, counter);
});
var next = document.createElement('a');
next.textContent = 'Next';
next.className = 'next';
next.addEventListener('click', function() {
newIndex = (that.currentIndex !== that.imgs.length-1) ? that.currentIndex+1 : 0;
that.changeImg(newIndex, counter);
});
controls.appendChild(prev);
controls.appendChild(next);
controls.appendChild(counter);
return controls;
},
changeImg: function(newIndex, counter) {
this.imgs[this.currentIndex].style.display = 'none';
this.imgs[newIndex].style.display = 'inline';
this.currentIndex = newIndex;
this.setCounter(counter);
},
setCounter: function(counter) {
counter.textContent = (this.currentIndex+1)+' / '+this.imgs.length;
}
};