I'm trying to build a very basic slider. I managed to create something but I am stuck when I try to change from one slide to another. I was thinking my code would work but it does not and I don't understand why.
Here's a link to a codepen of it
Here's the relevant part of my problem:
I have defined a slider like so:
var carrousel = document.getElementById('carrouselcontainer');
var slide1 = document.createElement('div');
slide1.className = 'slide1';
var slide2 = document.createElement('div');
slide2.className = 'slide2';
var slide3 = document.createElement('div');
slide3.className = 'slide3';
var slider = [slide1, slide2, slide3]
carrousel.appendChild(slider[0]);
And this does work. Now I am trying to add a function that will increment or decrement the slider variable when clicked.
var backButton = document.getElementById('backButton');
var forwardButton = document.getElementById('forwardButton')
function forward() {
slider++
}
forwardButton.addEventListener('click', forward)
But when I click on the forwardButton element, nothing happens. I know that the eventListener is working since I tried a window.alert() message on it and it works when I click it. What is it that I am doing wrong here?
Incrementing an array will not work but only generate error.
forward() should remove the actual child of the carrousel and
add a new child that has as value the next element of the slider array:
Introduce a currentSlide number variable to indicate the current index displayed and increment it in forward().
var currentSlide = 0;
...
carrousel.appendChild(slider[currentSlide]);
...
function forward() {
carrousel.removeChild(slider[currentSlide++]);
if (currentSlide >= slider.length){
currentSlide = 0;
}
carrousel.appendChild(slider[currentSlide]);
}
You need some kind of index which you use to get something out of your array:
var forwardButton = document.getElementById('forwardButton');
var result = document.getElementById('carrouselcontainer');
var sliderIndex = 0;
var slider1 = document.createElement("div");
slider1.innerHTML = "item 1";
var slider2 = document.createElement("div");
slider2.innerHTML = "item 2";
var slider3 = document.createElement("div");
slider3.innerHTML = "item 3";
var slider = [slider1, slider2, slider3];
result.appendChild(slider[sliderIndex]);
function forward() {
result.removeChild(slider[sliderIndex]);
sliderIndex = (sliderIndex + 1) % slider.length;
result.appendChild(slider[sliderIndex]);
}
forwardButton.addEventListener('click', forward);
<button id="forwardButton">Increment</button>
<div id="carrouselcontainer"></div>
You have to replace the element only incrementing the element does not work:
I added a counter "silderPos" to your script, so you can increment it by one on every click.
If it larger then 2 it will go back to 0 by a modulo action.
I made the carrouselElement global, so that your click script can access the element directly.
With this changes i can now go throu all of your element.
Please find the modified source code here:
var carrouselElement;
var sliderPos = 0;
function carrousel()
{
carrouselElement = document.getElementById('carrouselcontainer');
var slide1 = document.createElement('div');
slide1.className = 'slide1';
var slide2 = document.createElement('div');
slide2.className = 'slide2';
var slide3 = document.createElement('div');
slide3.className = 'slide3';
var slider = [slide1, slide2, slide3]
carrouselElement.appendChild(slider[0]);
var backButton = document.getElementById('backButton');
var forwardButton = document.getElementById('forwardButton')
function forward() {
carrouselElement.lastChild.remove();
sliderPos++;
sliderPos = sliderPos % 3;
carrouselElement.appendChild(slider[sliderPos]);
}
/*backButton.addEventListener('click', back)*/
forwardButton.addEventListener('click', forward)
}
window.addEventListener('load', carrousel);
Related
I'm trying to make a container div for each image and its description at each iteration in my for loop, but JQuery is lumping all the image divs and description divs together into one container div, and that's messing up the whole layout.
I'm not sure why it's doing that, especially since I'm creating a new container div and appending to it within the for loop.
Here's the JSFiddle: https://jsfiddle.net/ZEZEME/wza7q3tn/4/
HTML
<div class=PgTwo></div>
JS
$.getJSON(url, function(data) {
arr = data.data;
for (var i = 0; i < arr.length; i++) {
var articleInfo = arr[i];
console.log(articleInfo);
var imgURL = articleInfo["listingimage"]['url'];
var title = articleInfo["title"];
var desc = articleInfo["listingdescription"];
if (imgURL != "") {
var imgWrapperDiv = document.createElement('div');
var imgDiv = document.createElement('div');
var descDiv = document.createElement('div');
imgDiv.id = 'imgDiv';
imgWrapperDiv.id = 'imgWrapperDiv';
descDiv.id = 'descDiv';
descDiv.textContent = desc;
var imgurlCSS = 'url("'+imgURL+'")';
$(imgDiv).css({'background-image': imgurlCSS, 'background-repeat': 'no-repeat', 'background-size': 'cover'});
$(imgDiv).append($('<a href="" id=link >'+ title +'</a>').css('text-decoration', 'none'));
$('#imgWrapperDiv').append(imgDiv);
$('#imgWrapperDiv').append(descDiv);
$('.PgTwo').append(imgWrapperDiv);
}
}
});
You're only using one id in the for loop. So you're creating the wrapper div, then setting its id but every time it sets it to the same id as before. In the DOM only one wrapper div is present then.
As an experiment for a larger project, I am trying to make a text battle (it's in progress). What I need is when I press the button, it prints the text into a <p> tag. Also, it makes two buttons, one that says ATTACK and the other says SPARE. How would I
disable the initial onclick event from the button so I don't keep on making new buttons
add an onclick event to the new ones so I could run a different function.
This is my code:
HTML:
<button id = 'button' onclick='enemy()'>button</button>
And my JavaScript:
// PLAYER
var playerHP = 100;
var playerAt = 10;
var playerDef = 0;
//ENEMY
var enemyHP = 50;
var enemyAt = 5;
//FIGHT
function enemy() {
document.getElementById("test").innerHTML = "You encounter a wild MONSTER(AT:5 ¦ HP:50). Will you attack?";
for (var i = 0; i < 1; i++) {
var btnAt = document.createElement('BUTTON');
var t = document.createTextNode('Attack!');
btnAt.appendChild(t);
document.body.appendChild(btnAt);
var btnSp = document.createElement('BUTTON');
var d = document.createTextNode('Spare!');
btnSp.appendChild(d);
document.body.appendChild(btnSp);
}
}
Ignore some of the stuff- its for future use.
P.S. No jQuery, please, unless it is unavoidable.
something like this using .Disabled to disable the button, so you dont have to clear out the onclick for later use. and just set .onclick to whatever function you want on the button you built. I also recommend not trying to avoid jquery... Once you start using it, you can relize how much easier it can make your life. Also, why the loop?
// PLAYER
var playerHP = 100;
var playerAt = 10;
var playerDef = 0;
//ENEMY
var enemyHP = 50;
var enemyAt = 5;
//FIGHT
function enemy() {
document.getElementById("test").innerHTML = "You encounter a wild MONSTER(AT:5 ¦ HP:50). Will you attack?";
var btnAt = document.createElement('BUTTON');
//set onlick for button
btnAt.onclick = function()
{
//do stuff here
}
var t = document.createTextNode('Attack!');
btnAt.appendChild(t);
document.body.appendChild(btnAt);
var btnSp = document.createElement('BUTTON');
var d = document.createTextNode('Spare!');
btnSp.appendChild(d);
document.body.appendChild(btnSp);
//disable button
var originalbtn = document.getElementById("button").disabled = true;
}
I'm creating an image that changes on click. My code isn't working whats wrong with it?
<div id="img"></div>
<script>
var fNames = ["SD1", "SD2", "SD3", "SD4"]; //File names
var _img = document.getElementById("img"); //Grabs images, groups them
var imgIdx = 0;
_img.style.position = "relative";
_img.style.left = "auto";
_img.style.right = "auto";
_img.style.width = "1920";
_img.style.height = "1280";
_img.style.backgroundImage = "url('images/"+fNames[imgIdx]+".jpg')"; //Retrieves images from file
_img.addEventListener("click", onImageClick); //Allows image click
function onImageClick() {
imgIdx++;
if(imgIdx == 6) {
imgIdx = 0;
}
_img.style.backgroundImage = "url('images/"+fNames[imgIdx]+".jpg')";
}
</script>
You need a unit when you specify the size:
_img.style.width = "1920px";
_img.style.height = "1280px";
When making the index wrap around you are using 6, but it should be 5. Better yet, use the length of the array, that way you don't need to change that part of the code if the array changes:
if(imgIdx > fNames.length) {
imgIdx = 0;
}
I want to create elements inside another element until condition is true.
I have tried this code but it's not working.
// calculate span size and it's parent
var homeHeight = $(".home").height();
var homeWidth = $(".home").width();
var homeSize = (homeHeight + homeWidth) * 2;
var spanHeight = $(".back-animation span").height();
var spanWidth = $(".back-animation span").width();
var spanSize = (spanHeight + spanWidth) * 2;
// create span elements to fill it's parent.
var createSpan = function() {
var span = document.createElement("span");
while (spanSize <= homeSize) {
$(".animation-hide-overflow").append(span);
spanSize = spanSize + spanSize;
}
};
createSpan();
Note: It's combined with JQuery and I recieve no errors in console.
Note 2: I tried for loop like the bottom but it's not working either.
for (spanSize; spanSize <= homeSize; spanSize = spanSize + spanSize) {
$(".animation-hide-overflow").append(span);
}
EDIT:
Thanks for mentioning, I forgot to call createSpan function! now it's working but it create span just once. Any solutions?
jsfiddle for better demonstration:
http://jsfiddle.net/pooria_h/vqmgmyj0/1/
(It should keep creating span elements until it fills up parent element.)
The problem was this section
// create span elements to fill it's parent.
var createSpan = function() {
var span = document.createElement("span");
while (spanSize <= homeSize) {
$(".animation-hide-overflow").append(span);
spanSize = spanSize + spanSize;
}
}
If you pay more attention you can see I've created span variable outside of the loop, So this is what happens: Loop works correctly and it increases spanSize variable until it equals to homeSize variable which is bigger in the start point but the big problem is there isn't a element creation! span element is created before the loop.
So this is the correct way:
// create span elements to fill it's parent.
var createSpan = function() {
while (spanSize <= homeSize) {
var span = document.createElement("span");
$(".animation-hide-overflow").append(span);
spanSize = spanSize + spanSize;
}
}
I'd like to have a div become visible on a button click and have a setInterval append periods to show loading. I would also like a button to clear that interval and hide the div that shows up.
here's a fiddle
http://jsfiddle.net/4qx4r/4/
here's code:
function ProgressBar(){
var div;
var start = function(){
var count = 0,
div = $('#divNotification').show().text('Uploading').css('align','center'),
originalText = div.text(),
count = 0;
var beginCount = setInterval(function(){
var newText = div.text() + '.';
div.text(newText);
count++;
if(count > 5){
div.text(originalText);
count =0;
}
console.log(count);
},500)
}
var stop = function(){
console.log('stop');
div.hide();
window.clearInterval(beginCount);
}
this.start = start;
this.stop = stop;
}
var progressBar = new ProgressBar();
$('#btnStart').click(function(){
progressBar.start();
});
$('#btnStop').click(function(){
progressBar.stop();
});
Currently when I click btnStop I get `cannot read property hide of undefined'. How can I make this stop the interval and hide the div?
You are setting var beginCount within a function, therefore that variable is only accessible within that function.
Try declaring that variable outside or simply just remove the var part.
I would add it next to var div declaration
Also you need to replace commas with semicolons and your div is not set to the object, try the following:
var count = 0;
div = $('#divNotification');
div.show().text('Uploading').css('align','center');
originalText = div.text();
count = 0;
http://jsfiddle.net/4qx4r/6/
this works: http://jsfiddle.net/W8ySn/3/
I separated the initial div assignment:
div = $('#divNotification');
var count = 0;
div.show().text('Uploading editor').css('align','center');
originalText = div.text();
count = 0;