Basic Image Viewer with javaScript - javascript

I am new with JavaScript and I am trying to learn by coding. I want to make a basic image viewer with a "next" and a "previous" that you can click to move forwards and back through a gallery of ten pictures. So I have my html, my css and my javaScript files and 10 random pictures to try it out.
The files are pretty straight forward:
HTML:
<body>
<div id="wrap">
<div class="firstColumn">
<p>PHOTOGRAPHY</p>
<div class="firstColumnSub">
<p class="photo">SOME TITLE</p>
</div>
</div>
<div class="back">
<p>BACK</p>
</div>
<div id="container">
<div id="controllers">
<div class="buttons" id="previous">
<p onclick="change(-1);">PREVIOUS</p>
</div>
<div class="buttons" id="next">
<p onclick="change(1);">NEXT</p>
</div>
</div>
<div><img height="100%" id="front" src="Image1.jpg"></div>
<div>
<p id="footer">Footer</p>
</div>
</div>
</div>
</body>
Just a few divs with the image in the center and a previous and a next clickable tags. This is what it loos like:
The JavaScript file contains a function that loads the different pitures and -and this is my problem- centers them in the middle of the page by grabbing their width and updating the css:
JavaScript:
window.onload = function setUp() {
var b = document.getElementById("front").width;
document.getElementById("container").style.width = b + "px"
}
var imageCount = 1;
function change(x) {
imageCount = imageCount + x;
var image = document.getElementById('front');
var str1 = "Image";
var str2 = imageCount;
var str3 = ".jpg"
var sum = str1.concat(str2, str3);
image.src = sum;
var a = document.getElementById("front").width;
document.getElementById("container").style.width = a + "px"
}
I an not posting the css unless required, but you get the idea.
As you press "next" or "previous", you are supposed to get this result:
etc... but instead I get all sort of random displays:
And here is the thing that is puzzling me: if you keep clicking "back" and "next", the same pictures appear OK the second time round, so it is working but not immediately. Any help appreciated!
Thanks, P.

This is most likely a CSS positioning issue. The following CSS may do the job for you. If you need further help, then I suggest that you reconsider posting your CSS to get help.
#container #front
{
position: relative;
/* width: 0px; */ /* set via JS for each element in this use case */
left: 0;
right: 0;
margin: 0 auto;
}
Here is a popular Q & A on this subject which contains a lot of resources.

Related

Open third party Live chat on the same page without opening a separate window

Target Environment: Wordpress VIP
header.php
goal: click icon div to open third party chat, toggle to close if needed, chat icon to persist acrross all pages.
Hi All
I've been tasked with integrating a 3rd Party Chat app in our site. I want it to perform like a traditional chat in-page chat app (in a div) , however, the shared script uses js the window.open method and open the chat into a separate window. I've tried unsuccefully to use , tags.
Suspect this shouldnt be to hard but I can't figure it out. I hope I have enough information here.
Thanks in advance!
The code I am replacing is straight forward yet opens into a new window but I need the window to look like a modern chat
script type="text/javascript "
const chatFunc = () => {
var x = screen.width - 550;
var y = screen.height - 800;
var params = 'height=550,width=375,popup=yes,left='+x+',top='+y;
var Url = 'thridpartychat link';
**window.open(Url, '', params);** // this seems to be the issue
}
script
<div id="test" class="chat" onClick="chatFunc()" data-toggle="tooltip" data-placement="top" title="Chat" style=""> </div>
My attempt:
<div id="test" class="chat fas fa-comment-dots fa-7x embed-responsive" data-toggle="tooltip" data-placement="top" title="Chat now!" style="">
<iframe id="chatIframe" class="embed-responsive-item" style="border:none" seamless>
</iframe>
</div>
var x = screen.width - 550;
var y = screen.height - 800;
var params = "height=550,width=375,popup=yes,left=" + x + ",top=" + y;
var Url =
"[link to third Party Chat]";
var test = document.getElementById('test');
test.addEventListener("click", function() {
// Get Iframe - I had exception catch here -didnt work
var iframe = document.getElementById('chatIframe');
// Assign Attr-Used Object.assign at one point to no avail
iframe.setAttribute('left', '+' + x + '+');
iframe.setAttribute('top', '+' + y, );
iframe.setAttribute('height', '550');
iframe.setAttribute('weight', '375');
iframe.setAttribute('src', 'Url');
this.parentNode.appendChild(iframe);
this.parentNode.removeChild(this);
});
Here is how I want the chat to look :
No idea why you are over complicating this. is there a specific reason you want to load the iframe after? if not using css to style it and just toggling it to be visible is the best solution.
HTML
<body>
<header>
<button id="js-chat-toggle" class="chat fas fa-comment-dots fa-7x embed-responsive" data-toggle="tooltip" data-placement="top" title="Chat now!" style="">
Chat now!
</button>
</header>
<div class="chat-container" id="js-chat-container">
<iframe id="chat-iframe" class="embed-responsive-item" seamless src="https://google.com">
</div>
</iframe>
</body>
CSS
.chat-container {
display: none;
position: absolute;
bottom: 10px;
right: 10px;
max-width: 320px;
overflow:hidden;
}
.chat-container.open {
display: block;
}
.chat-container iframe {
width: 100%;
border: none;
overflow:hidden;
}
JavaScript
const chatToggle = document.getElementById('js-chat-toggle');
const chatContainer = document.getElementById('js-chat-container')
chatToggle.addEventListener('click', function() {
chatContainer.classList.toggle('open')
})

How to set order to arrays when I click next and previous on JavaScript?

I want to create a image viewer where you click next and previous to change the image.
So far the buttons next and previous changes the image. However when I click next then previous, the image doesn't go to the previous image instead it goes to the starting image.
My guess is to create a variable var = newImage and use that variable on function change2() and create a new varirable var= newImage2 and use that on function change().
is that possible?
<!DOCTYPE html>
<html>
<head>
<title>JS ChangeImage</title>
</head>
<body>
<h1 align="center">Change Image</h1>
<br>
<div class= "container" align="center">
<button onclick="change2()">Previous</button>
<img src="html5.png" style="height: 500px; width: 500px" id="changeimg">
<button onclick="change()">Next</button>
</div>
</body>
<script>
var img=0;
var imgArr = ["html5.png","css3.png","javascript.png"]
function change() {
var image = document.getElementById('changeimg');
console.log("current image =>", imgArr[img])
document.getElementById('changeimg').src =imgArr[img];
if (img== 2) img = 0;
else
img++;
}
function change2() {
var c1=
document.getElementById('changeimg').src =imgArr[img];
console.log("current image =>", imgArr[img])
if (img== 0) img = 2;
else
img--;
}
First, I noticed that you are changing the img variable after assigning the image to the element. I think you should switch the order. The way it is now, when you click Next, the number advances, but the picture is associated with the previous number. If you then click Previous, the number will reduce, but the image will appear to advance.
I've made some other changes for simplicity here:
HTML:
<h1 align="center">Change Image</h1>
<br>
<div class= "container" align="center">
<button onclick="change(event)" name='1'>Previous</button>
<img src="html5.png" style="width: 500px" id="changeimg">
<button onclick="change(event)" name='2'>Next</button>
</div>
JS:
var currentImg = 0;
const imgArr = ["html5.png","css3.png","javascript.png"]
const change=(event)=>{
if(event.target.name==='1'){
currentImg>0?currentImg--:currentImg=2;
} else if(event.target.name==='2'){
currentImg<imgArr.length-1?currentImg++:currentImg=0;
}
console.log(currentImg);
document.getElementById('changeimg').src = imgArr[currentImg];
}
Please note the use of the 'name' attribute of the for use in the logic of the change function. This allows me to use only one function for both buttons. I hope this helps.

how to change the src of an image when clicking and it return to the original after some time?

I have a page that displays several hidden divs when clicking on image-buttons (next and previous). sometimes takes a few seconds for its content to show up correctly, so I had the idea of ​​delaying the functions a bit to "give time" for the content to "prepare". While that time the image exchanges for a gif.
I already started and saw that it works, I got a simple way with tris.src to change the img and setInterval for the delay, direct on my onclick="", but I need the original image to automatically return to the original after 2 or 3 seconds because it can showed again (when clicked on previous button) and should not to be a gif anymore! and don't know how to do this. can you help me?
CSS:
div1, #div2 {width: 100px; height: 100px; background: yellow;position: relative;
next {position: absolute bottom: 20px; left: 20px}
}
HTML & JS:
<div id="div1">
content1
<img src="next.png" id="next" onclick="setTimeout(replace, 1000); this.src='prev.png'">
<input type="hidden" value="prev.png" id="hdnPreviousPng" />
</div>
<div id="div2" style="display: none">content2
<img src="next.png" id="next" onclick="setTimeout(replace2, 1000); this.src='prev.png'">
<input type="hidden" value="prev.png" id="hdnPreviousPng" />
</div>
<script>
function replace() {
document.getElementById("div1").style.display="none";
document.getElementById("div2").style.display="block";
setInterval(function(){
let originalSrc = $('#hdnPreviousPng').val();
$('#next').attr('src', originalSrc);
}, 3000);
}
function replace2() {
document.getElementById("div2").style.display="none";
document.getElementById("div1").style.display="block";
setInterval(function(){
let originalSrc = $('#hdnPreviousPng').val();
$('#next').attr('src', originalSrc);
}, 3000);
}
</script>
You could just use a simple data attribute to store some state and swap in and out image source tags.
Here is an example of how this would work using JavaScript:
function clicked() {
replace();
setTimeout(replace, 1000);
}
function replace() {
var next = document.getElementById("next").getAttribute("data-img-src");
var current = document.getElementById("next").src;
document.getElementById("next").setAttribute("data-img-src", current);
document.getElementById("next").src = next;
}
<div id="div1">
<img id="next" src="http://via.placeholder.com/100?text=first" data-img-src="http://via.placeholder.com/100?text=second" onclick="clicked();">
</div>
If you need to account for multiple clicks and still return to the original image you will need some more state and can try this:
function clicked() {
replace();
setTimeout(replaceOriginal, 1000);
}
function replace() {
var next = document.getElementById("next").getAttribute("data-img-src");
document.getElementById("next").src = next;
}
function replaceOriginal(){
var original = document.getElementById("next").getAttribute("data-img-original");
document.getElementById("next").src = original;
}
<div id="div1">
<img id="next" src="http://via.placeholder.com/100?text=first" data-img-original="http://via.placeholder.com/100?text=first" data-img-src="http://via.placeholder.com/100?text=second" onclick="clicked();">
</div>

Reload a DIV on click of another DIV

I have a div called masterdiv, inside this div there are 3 other div div1, div2, and div3,
This is the html for these html:
<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>
</div>
I also have another div:
<div id=”reload”><img src="reload.png" width="200" height="70" onclick=loadDIV();></div>
What I’m trying to do is to reload the masterdiv div whenever the reload div is clicked on. Hiding and then showing the div isn’t enough as I need the content to be reloaded when the refresh div is clicked on. I don’t want to reload the entire page, just the masterdiv which contains the 3 other div. But I’m not certain this is possible.
I’m trying to do it with this Javascript function:
<script type="text/javascript">
function loadDiv(){
$("<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>
</div>").appendTo("body");
}
</script>
This isn’t working, I think maybe I'm going about this in the wrong way? Maybe I’m missing something very simple here? I’d really appreciate any help with this, thank you in advance!
UPDATE
After reconsidering my project's requirements, I need to change part of my question, I now need to randomise the images displayed in the divs, and have a new random image load every time the reload div is clicked on. I also need to remove each class that’s currently in each of the three divs and then reattach the same classes to the divs (if I don’t remove and reattach the classes then the divs just display the plain images without any class/effect applied to them, it seems like I need to reload the class every time I load an image into a div in order for the class/effect to be applied successfully).
I have 5 images, and I’m using each div’s id tag to attach a random image to each div.
First I’m assigning the 5 different images to 5 different ids:
<script>
document.getElementById('sample1').src="images/00001.jpg";
document.getElementById('sample2').src="images/00002.jpg";
document.getElementById('sample3').src="images/00003.jpg";
document.getElementById('sample4').src="images/00004.jpg";
document.getElementById('sample5').src="images/00005.jpg";
</script>
And then I’m trying to use the following Javascript to load a randomised id (and its assigned image) to each of the 3 divs when the reload div is clicked:
<script>
$(function() {
$('#reload').on('click',function(){
$("#masterdiv").find("div[id^='div']").each(function(index){
//First, remove and reattach classes “div1class”, “div2class” and “div3class”
//from “easyDIV”, “mediumDIV” and “hardDIV” respectively:
$(“#easyDIV”).removeClass('div1class');
$(“#easyDIV”).addClass('div1class');
$(“#mediumDIV”).removeClass('div2class');
$(“#mediumDIV”).addClass('div2class');
$(“#hardDIV”).removeClass('div3class');
$(“#hardDIV”).addClass('div3class');
//Get a random number between 1 and 5, then attach it to “sample”,
//so that the result will be either “sample1”, “sample2”, “sample3”, “sample4” or “sample5”,
//call this variable “variablesample”:
var num = Math.floor(Math.random() * 5 + 1);
variablesample = "sample" +num;
//Attach this randomised id to all three divs using “variablesample”:
jQuery(this).prev("easyDIV").attr("id",variablesample);
jQuery(this).prev("mediumDIV").attr("id",variablesample);
jQuery(this).prev("hardDIV").attr("id",variablesample);
});
var p = $("#masterdiv").parent();
var el = $("#masterdiv").detach();
p.append(el);
});
});
</script>
I’m trying to make it so that all 3 divs will show the same randomised picture (that’s why they’re all sharing the variable “variablesample”), and each div will reload its own class/effect (div1class, div2class and div3class) but it’s not working. I’m not sure if it’s correct to use jQuery inside a Javascript function, or if my syntax for updating the ids of the divs is incorrect.
Perhaps my logic to solving this problem is all wrong? I’d really appreciate any more help with this problem. Thanks again in advance!
Original question was edited many times, so here is the correct answer for the latest edit. Answer to the question; "How to use random image, but same image on all 3, and 3 class on/off switching":
$(function() {
var imageArray = [
'https://via.placeholder.com/40x40',
'https://via.placeholder.com/80x40',
'https://via.placeholder.com/120x40',
'https://via.placeholder.com/160x40',
'https://via.placeholder.com/200x40'];
reloadImages(imageArray);
$('#reload').on('click',function(){
$( "#masterdiv img[id^='div']" ).each(function(index){
$(this).removeClass("div"+(index+1)+"class");
$(this).fadeOut( "slow", function() {
if(index==0) {
reloadImages(imageArray);
}
$(this).addClass("div"+(index+1)+"class");
$(this).fadeIn();
});
});
});
});
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function reloadImages(array){
shuffleArray(array);
for(var i=0;i<3;i++){
// places the first image into all divs, change 0 to i if you want different images in each div
document.getElementById('div'+(i+1)+'id').src=array[0];
}
}
.div1class {
border:2px dashed #0F0;
}
.div2class {
border:2px dashed yellow;
}
.div3class {
border:2px dashed red;
}
#reload {
background-color:blue;
color:white;
width:100px;
height:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='reload'>Click here</div>
<div id="masterdiv" class="masterdivclass">
<div id="div1">
<img src="https://via.placeholder.com/20x40" class="div1class" id="div1id" />
</div>
<div id="div2">
<img src="https://via.placeholder.com/20x40" class="div2class" id="div2id" />
</div>
<div id="div3">
<img src="https://via.placeholder.com/20x40" class="div3class" id="div3id" />
</div>
</div>
Line breaks and un-escaped quotes are why the functions is not working.
function loadDiv(){
$('#masterdiv').remove();
$("<div id='masterdiv' class='masterdivclass'><div id='div1'><img class='div1class' src='image1.jpg' id='div1id' /></div><div id='div2'><img class='div2class' src='image2.jpg' id='div2id' /></div><div id='div3'><img class='div3class' src='image3.jpg' id='div3id' /></div></div>").appendTo("body");
}
try:
function loadDiv(){
$("#masterdiv").load(location.href + " #masterdiv");
}
Here's the code pen demo:
http://codepen.io/anon/pen/xwgRWm
If content of container is not being changed dynamically then there is no point reloading it. appendTo wiil append DOM in existing DOM structure, you will need html() here which will replace the content inside container. Also note you had typo here onclick=loadDiv();
HTML:
<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id"/></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id"/></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id"/></div>
</div>
<div id="reload"><img src="reload.png" width="200" height="70" onclick=loadDiv();></div>
JS:
function loadDiv() {
$("#masterdiv").html('<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>\
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>\
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>');
}

How make a popup work

I am trying to develop a popup feature when you click on an Image the image opens up as a popup. Here is the example
http://soumghosh.com/otherProjects/natalierosscms/175-2/
Click on the first image and close it. Then click on the second image. The images are repeating. Any ideas what I am doing wrong? For some reason I am not able to post code here.
JavaScript:
$('.alignnone').click(function(){
$('.overlay').appendTo('body');
$('.overlay').show();
var popImage = $('.projectContainer').show();
var thumbHolder = $(this).parent();
thumbHolder.css('position', 'relative');
$(this).clone().appendTo('.projectContainer');
var cssAtrOne = {
padding:'10px',
width:'110%'
};
popImage.appendTo(thumbHolder).css(cssAtrOne);
});
$('.closeButton').click(function(){
$('.overlay').hide();
$('.projectContainer').hide();
});
HTML:
<!-- clickable image -->
<img src="http://soumghosh.com/otherProjects/natalierosscms/wp-content/uploads/2013/03/T1Main.jpg" alt="T1Main" width="559" height="745" class="alignnone size-full wp-image-181">
<!-- popup -->
<div class="projectContainer" style="padding: 10px; width: 110%; display: block;">
<img class="closeButton" src="/otherProjects/natalierosscms/wp-content/themes/twentyeleven/images/closeButton.png">
</div>
You have this:
$(this).clone().appendTo('.projectContainer');
You're appending the image to the projectContainer without clearing the projectContainer first (So images just continue to build up each time). So what you'll need to do is clear out the previous images, then insert the new one.
But inside projectContainer is your close button, which makes things a wee bit tricker. There are many ways to work around this issue, but a straight-forward solution would be to introduce another <div>, imageContainer inside projectContainer:
HTML:
<div class="projectContainer" style="display: none; padding: 10px; width: 110%;">
<img class="closeButton" src="/otherProjects/natalierosscms/wp-content/themes/twentyeleven/images/closeButton.png">
<div class="imageContainer"></div>
</div>
Then modify your JS:
Change JS:
//REPLACE the contents of imageContainer, not append to it.
//$(this).clone().appendTo('.projectContainer');
$('.projectContainer > .imageContainer').html($(this).clone());
Something to that effect should work.

Categories