Adding Next & Previous Buttons to modal with JavaScript - javascript

I have made a clean modal to use on a website to open images, everything works fine and is pretty nice.
Now I want to make a next image and previous image button for a better user experience.
I have a plan, so I find the index of the current image that is in the modal and I increment it by one on the next button, and decrement it by one on the previous button, HM ok seems easy enough. So how do I go about doing this?
this is my Modal code
window.onload = function() {
var imgArr = document.getElementsByClassName("myImg");
var modalWindow = document.getElementById("myModal");
var modalImg = document.getElementById("img01");
var caption = document.getElementById("caption");
var span = document.getElementById("close");
var modalBlock = document.getElementById("modalBlock");
for (i = 0; i < imgArr.length; i++) {
var picture = imgArr[i];
var list = Array.from(imgArr);
picture.onclick = function() {
openImg(this);
var index = list.indexOf(this);
console.log(index);
};
}
function openImg(pic) {
modalWindow.style.display = "block";
modalBlock.style.transform = "translateY(0%)";
modalImg.src = pic.src;
modalImg.alt = pic.alt;
caption.innerHTML = modalImg.alt;
imgIndex = picture[i];
bodyScrollLock.disableBodyScroll(myModal);
}
};
Now I have the open image that I've clicked on and its index, and I'm stuck on what to do next. I've found the w3 lightbox tutorial, but it's so different from my code I need to swap everything. Does anyone have an idea how I can do this with my own code?
A jsFiddle how it looks at the moment
https://jsfiddle.net/superVoja/eoyda1vh/15/

If you insist on building this from scratch then you will need to start thinking about what you should control with HTML and CSS and leave the rest to do with JavaScript.
I would use Modal window set with Html and hide it with CSS, then when image link and trigger fires I would bring modal to front. Using fadein fadeout, opacity and z-index to make sure that is on the front. Set background to black in order to get the Modal effect.
The faster way is to use library like Lightbox js
Then overwrite using CSS and maybe some js if need to in order to adjust to your liking.

Well, here is the answer I got myself if anyone reads this give yourself some time, you'll find the answer yourself!
I followed my code and did exactly the thing I was trying to do, I found the index of the image that is clicked, and then I just incremented it by one like this.
var next = this.document.getElementById("next");
var slideIndex = "";
for (i = 0; i < imgArr.length; i++) {
var picture = imgArr[i];
var list = Array.from(imgArr);
picture.onclick = function() {
var index = list.indexOf(this);
slideIndex = index;
openImg(imgArr[index]);
console.log(index);
};
}
next.addEventListener("click", function(event) {
openImg(imgArr[(slideIndex += 1)]);
});
It may not look pretty, but it's mine and I am proud of it!
And here is a link How it looks!

Related

Javascript click on specific element always uses wrong/other element id

I have several html pages and each one has a varying number of buttons that appear based on the page's content.
In just Javascript (since I don't use jquery), I am trying to have the same few lines of code apply to the respective button that was clicked, with the exception that the id tag has to be 'concatenated' into a variable based on the respective button that was clicked.
I saw other solutions on here that cycled through the elements of the class (in this case the "zoom_buttonClass"). However, when I attempt this, regardless of number of buttons on the page or which button was clicked, it is always the LAST button in the list that seems to be the one seen as clicked.
I need to always check if buttons are clicked, but how do I apply the actions based on the ACTUAL button that was clicked?
My HTML and JS code snippets are below:
Thanks in advance.
HTML code:
<div class="modalClass" id="myModalID">
<span class="closeModalClass" aria-label="Close Photo Enlargement Modal Box">×</span>
<img class="modal_contentClass" id="modalEnlargementID">
</div>
<div id="captionID"></div>
JS code:
for (var i = 0;i < document.getElementsByClassName("zoom_buttonClass").length;i++){
document.getElementsByClassName("zoom_buttonClass")[i].addEventListener('click', myFunction
(var attribute = this.getAttribute("id");
var photoIDstring = "photo"+counterX+"ID";
document.getElementById('myModalID').style.display = "block";
document.getElementById('captionID').style.display = "block";
document.getElementById("modalEnlargementID").src = document.getElementById(photoIDstring).src;
captionText.innerText = document.getElementById(photoIDstring).alt;
), false);
};
Well, I started again and I think I may have hit upon a solution. It seems to work.
var captionText = document.getElementById("captionID");
var howManyButtons = document.getElementsByClassName("zoom_buttonClass").length;
var buttonCollection = document.getElementsByClassName("zoom_buttonClass");
for (let i=0; i < howManyButtons; i++) {
buttonCollection[i].onclick = function() {
let photoIDstring = "photo"+(i+1)+"ID";
document.getElementById('myModalID').style.display = "block";
document.getElementById('captionID').style.display = "block";
document.getElementById("modalEnlargementID").src = document.getElementById(photoIDstring).src;
captionText.innerText = document.getElementById(photoIDstring).alt;
}
}

JavaScript - Toggle function

Im trying to hide/show a JS function I have defined in a chrome extension.
What I have so far:
The span classes I am trying to hide are label:
dspan.className = "cExtension";
//Create toggle button:
function createToggleButton(){
var toggleButton = document.createElement("button");
toggleButton.innerHTML = "Toggle Overlay";
toggleButton.id = "Toggle"
var header = document.getElementById("header");
header.appendChild(toggleButton);
toggleExtension();
}
// find all spans and toggle display:
function toggleExtension(){
var spans = document.getElementsByTagName('span');
var toggle = function() {
for (var i = 0, l = spans.length; i < l; i++) {
if (spans[i].getAttribute('class') == 'cExtension')
if (spans[i].style.display == 'none') spans[i].style.display = '';
else spans[i].style.display = 'none';
}
}
document.getElementById('Toggle').onclick = toggle;
}
The button shows on the header, however it is unclickable. If I change document.getElementById('Toggle').onclick = toggle; to document.getElementById('Toggle').onclick = alert{"Hello"); the alert is triggered on page load on not onclick. I am trying to get this done in pure JS. Where am I going wrong?
First of all, document.getElementById("Toggle").onclick = alert("Hello"); will set the onclick event to whatever the alert function returns, not the alert function itself. So the alert function happens at page load so it can figure out what to return. So you could do this: document.getElementById("Toggle").onclick = function(){alert("Hello");}; and that might work.
Edit: Scratch everything that was here: I missed that toggle variable set to a function in toggleExtension.
I haven't tested all this so I can't guarantee that it'll all work in your specific case.
if visible is set remove it, otherwise add it
div.classList.toggle("visible");
add/remove visible, depending on test conditional, i less than 10
div.classList.toggle("visible", i < 10 );
Make sure browser support: http://caniuse.com/#feat=classlist
Why not use jQuery?
It will do all hard job for you.
http://api.jquery.com/toggle/
Cheers!

css3 animation on click with javascript

I need to animate several items at the same time, several times on click. I'm not allowed to use Jquery so I'm working with native javascript and CSS3.
Array.prototype.forEach.call(els, function(el) {
elemId = el.getAttribute("id");
var toWidth = boxPos[thisId][elemId].width;
var toHeight = boxPos[thisId][elemId].height;
var toTop = boxPos[thisId][elemId].top;
var toLeft = boxPos[thisId][elemId].left;
var from = "0% {width:"+currPos[elemId].width+"; height:"+currPos[elemId].height+"; top:"+currPos[elemId].top+"; left:"+currPos[elemId].left+";}";
var to = "100% { width:"+toWidth+"; height:"+toHeight+"; top:"+toTop+"; left:"+toLeft+";}";
currPos[elemId].width = toWidth;
currPos[elemId].height = toHeight;
currPos[elemId].top = toTop;
currPos[elemId].left = toLeft;
var styleSheets = document.styleSheets;
for (var i = 0; i < styleSheets.length; ++i) {
for (var j = 0; j < styleSheets[i].cssRules.length; ++j) {
if (styleSheets[i].cssRules[j].type == window.CSSRule.WEBKIT_KEYFRAMES_RULE && styleSheets[i].cssRules[j].name == elemId){
keyframes = styleSheets[i].cssRules[j];
}
}
}
keyframes.deleteRule("0%");
keyframes.deleteRule("100%");
keyframes.insertRule(from);
keyframes.insertRule(to);
el.style.webkitAnimationName = elemId;
});
I've searched around the site and have tried using some of the code. The animation will run once, all the elements but just the first time :'(
Here's a non working example code http://jsfiddle.net/kR384/2/
The animation will run once, all the elements but just the first time
You seem to be looking for the animation-iteration-count CSS property, which specifies how often an animation will run. You can set it to infinite or any numerical (positive) value.
The problem you have with your animations is that they are only started on the first click. After that, you don't change the element's styles (reassigning the animation-name doesn't help) - so no animation will get triggered (even if you changed the keyframes rules). The article at http://css-tricks.com/restart-css-animation/ discusses this and a few solutions.
In your case it would even make sense to change the name of animation to something containing the "state":
if( …cssRules[j].name.split("-")[0] == elemId)
keyframes = styleSheets[i].cssRules[j];
…
var newname = elemId+"-"+thisId;
keyframes.name = newname;
…
el.style.animationName = newname;
(Demo with standard properties and a few bugfixes, updated demo with webkit prefixes)
I was able to fix it just by adding a setTimeout(0) to call the animation after the animation name was set to none.
Here's the fixed code http://jsfiddle.net/kR384/3/:
function resetAndRun(o){
one.style.webkitAnimationName = "none";
…
ten.style.webkitAnimationName = "none";
setTimeout(function(){o.animateBox();}, 0);
}
I hope it's useful for someone.

How to interate an array with navigation menu buttons (first, previous, next, last)

Well, one more question. Since I started learning javascript short time ago, I am almost obsessed trying new things! Here it goes:
Let's say that I have an array of strings and I want to iterate on it with a navigation menu with the buttons FIRST, PREVIOUS, NEXT, LAST.
Look at this code:
var thearray = ["article1", "article2", "article3"];
var thebody = document.getElementsByTagName('body')[0];
var divcontainer = document.createElement("div");
var divpage = document.createElement("div");
function generatepage(article) {
var paragraph = document.createElement("p");
var name = document.createTextNode(thearray[article]);
paragraph.appendChild(name);
divpage.appendChild(paragraph);
}
divcontainer.appendChild(divpage);
thebody.appendChild(divcontainer);
generatepage(0); // that would be for the first article
I also figured out that generatepage(thearray.length -1)would be the call for the last article, so I have solved two buttons (before generating new content I would erase it with innerHTMLbut what I cannot think about how to do are the PREVIOUS and NEXT buttons...
Do you have any suggestion about how should I get started to make working PREVIOUS and NEXT?
I attach a JSFiddle
Thank you so much for any advice!
You can save the active page in a variable outside the function:
var page = 0;
Then you don’t need to bring any page into generatepage():
function generatepage() {
var paragraph = document.createElement("p");
var name = document.createTextNode(thearray[page]);
paragraph.appendChild(name);
divpage.appendChild(paragraph);
}
Now you can control the page from outside the function:
var next = function() {
if ( page < page.length-1 ) { page++; }
}
var prev = function() {
if ( page ) { page--; }
}
So to show the first page:
page = 0;
generatepage()
And the next:
next();
generatepage()
etc.... There are other ways too of course but this might give you an idea.
You can save a variable outside the scope of the function to memorize the current article
when you add Eventlisteners to the buttons you can call the next and previous item
but you should somehow replace the content of the div with the next one instead of appending it (i don't know a thing about manipulating dom elements)
you could try something like this:
var thearray = ["article1", "article2", "article3"];
var thebody = document.getElementsByTagName('body')[0];
var divcontainer = document.createElement("div");
var divpage = document.createElement("div");
var currentarticle
function generatepage(article) {
if(thearray[article]) {
currentarticle = article
var paragraph = document.createElement("p");
var name = document.createTextNode(thearray[article]);
paragraph.appendChild(name);
divpage.innerHTML= paragraph.innerHTML
}else {
return false
}
}
divcontainer.appendChild(divpage);
thebody.appendChild(divcontainer);
generatepage(0); // that would be for the first article
document.getElementById("next").addEventListener("click",function() {
generatepage(currentarticle + 1)
});
document.getElementById("previous").addEventListener("click",function() {
generatepage(currentarticle - 1)
});
document.getElementById("last").addEventListener("click",function() {
generatepage(thearray.length - 1)
});
document.getElementById("first").addEventListener("click",function() {
generatepage(0)
});
​
heres the Fiddle

Variables within function is null

I have the following function:
function slideDown() {
//get the element to slide
sliding = document.getElementById('slideDiv1');
//add 1px to the height each time
sliding.style.height = parseInt(sliding.style.height)+1+'px';
t = setTimeout(slideDown,30);
if (sliding.style.height == "401px") {
clearTimeout(t);
}
}
which is called within this function:
function addDiv(nextImageSlide) {
//finds the src attribute of the image nested in the Li
elemChild = nextImageSlide.firstChild;
imageSrc = elemChild.getAttribute('src');
//loops and creates six divs which will be the slices. adds background property etc
for (i = 0, j = 0, k = 1; i< = 19; i++, j++, k++) {
var newDiv = document.createElement('div');
newDiv.setAttribute('class', 'new-div');
newDiv.id='slideDiv' + k;
newDiv.style.height = '1px';
newDiv.style.background = 'url(' + imageSrc +') scroll no-repeat - '+39.5 * j + 'px 0';
var a = document.getElementById('content');
a.appendChild(newDiv);
}
slideDown();
}
Which is called within another function that defines nextImageSlide. It later removes all the divs that it just made.
The idea is for an image gallery. When the user hits the next button, I want slices of the next image to slide down to show the next image. Those slices are then taken away and the new image revealed.
I would like something like this: http://workshop.rs/projects/jqfancytransitions/.
It's for an assignment so we have to write all the code ourself and this is the best way I can think to replicate it. The only problem is that I keep getting an error:
'sliding is null. sliding.style.height = parseInt(sliding.style.height)+1+'px';'
No matter what I do I can't get rid of it. The thing is if I define sliding as a totally different id, (for example I made a random little div outside of everything), it working.
This error shows when I try to access the divs, it just made that it throws a hissy fit.
Anyone see any errors in my code?
Hopefully this is just a typo while pasting into the site here, but:
car a = document.getElementById('content');
^---syntax error, which'll kill your entire script - var?

Categories