Basically I want to add a "x" , a close button, at the top right of an image that will appear after some time using setTimeout(). So when you click on the x button, it will close the image. I played around with <input type="image"> but it isn't what I wanted because it makes the image clickable. I've looked at examples but I'm not sure how to approach this. Thank you for any help.
function showImage(){
document.getElementById('banner').style.display = 'inline-block';
}
setTimeout(showImage,3000);
<figure class = "showBanner">
<input type="image" id="banner" src="https://i0.wp.com/wptavern.com/wp-content/uploads/2016/07/stack-overflow.png?ssl=1" style="display:none"/>
<script type = "text/javascript" src = "testing.js"></script>
</figure>
First of all: The <input type="image" ... /> is for formulas when you want to have a button with background-image. As far as I understand, that is not at all what you want.
Also, use a separate css-file for your styles!
This example should solve your problem:
function showButton(){
document.getElementById('xButton').style.display = 'block';
}
document.getElementById('xButton').addEventListener("click", function(){
document.getElementById('banner').style.display = 'none';
document.getElementById('xButton').style.display = 'none';
});
setTimeout(showButton,3000);
#xButton {
float: right;
display: none;
}
.showBanner {
width: 50%;
}
<figure class = "showBanner">
<button id="xButton"> x </button>
<img src="https://i0.wp.com/wptavern.com/wp-content/uploads/2016/07/stack-overflow.png?ssl=1" id="banner" width="100%">
</figure>
You could try changing the opacity from 0 to 1 on click, this way you can use css transitions too
style="opacity:0"
banner.style.opacity = '1';
As for the button you can use the x symbol
<span class="closeBtn">×</span>
const closeBtn = document.querySelector('.closeBtn');
closeBtn.addEventListener('click', () => banner.style.opacity = '0');
Related
I am new to JavaScript. I created this code in order to try and make buttons that will hide
and show certain pictures on the page. I have 3 buttons, the first of which is supposed to run my JavaScript code in <script></script> tags, the other two just have Javascript code inside them and they work fine. But they don't hide the picture once they are clicked a second time, which is why I am trying to do that for the first one if possible.
For some reason, I cannot get the first button with "open()" to work the way I want with my Javascript code. Can anyone with more experience please explain to me what I am doing wrong? Thank you in advance...
var btn1 = document.getElementById('1');
var btn2 = document.getElementById('2');
var btn3 = document.getElementById('3');
var display1 = btn1.getAttribute('display')
var display2 = btn2.getAttribute('display')
var display3 = btn3.getAttribute('display')
function open() {
if (display1 === ('none')) {
btn1.setAttribute('display', 'block');
} else {
btn1.setAttribute('display', 'none');
}
}
<img id="1" src="forge.PNG" style="height:320px; display:none; padding:10px">
<img id="2" src="lizard.jpg" style="height:320px; display:none; padding:10px">
<img id="3" src="walkway.jpg" style="height:320px; display:none; padding:10px">
<button onclick="open()">1</button>
<button onclick="document.getElementById('2').style.display='block'">2</button>
<button onclick="document.getElementById('3').style.display='block'">3</button>
I'd use event delegation to watch for clicks on the container. When the nth button is clicked, select the nth image, and toggle a class that hides/shows the image:
const images = document.querySelectorAll('img');
const buttons = [...document.querySelectorAll('button')];
document.addEventListener('click', (e) => {
if (e.target.matches('button')) {
const i = buttons.indexOf(e.target);
images[i].classList.toggle('hidden');
}
});
.hidden {
display: none;
}
<img id="1" src="https://www.gravatar.com/avatar/34932d3e923ffad9a4a1423e30b1d9fc?s=48&d=identicon&r=PG&f=1" style="height:320px; padding:10px" class="hidden">
<img id="2" src="https://www.gravatar.com/avatar/978ec0c47934c4b04401a8f4b4fec8bd?s=32&d=identicon&r=PG&f=1" style="height:320px; padding:10px" class="hidden">
<img id="3" src="https://lh3.googleusercontent.com/-uIr21N5ccCk/AAAAAAAAAAI/AAAAAAAAHeg/ohNEkpJKXQA/photo.jpg?sz=32" style="height:320px; padding:10px" class="hidden">
<button>1</button>
<button>2</button>
<button>3</button>
Problems with your original code include:
You're trying to select the elements before they exist in the DOM
Elements do not have a display property - in order to check the style of an element, you have to access its .style property first (eg, someImage.style.display)
Similarly, to set the style of an element, you have to set a property of its style property (eg someImage.style.display = <newDisplay>). Setting the display attribute of the element won't do anything.
Try to avoid inline handlers if at all possible - they have many problems and are pretty much universally considered to be quite poor practice. Always attach listeners properly using Javascript instead, whenever that's an option.
The event listener is the better solution, but if you want to see a working code in your way:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>switchpics</title>
</head>
<script type="text/javascript">
var open = function(param) {
img = document.getElementById(param.innerHTML);
if (img.style.display == 'none'){
img.style.display = "block";
} else {
img.style.display = "none";
};
};
</script>
<body>
<img id="1" src="1.jpg" style="height:20px; display:block; padding:10px">
<img id="2" src="1.jpg" style="height:20px; display:none; padding:10px">
<img id="3" src="1.jpg" style="height:20px; display:none; padding:10px">
<button onclick="open(this)">1</button>
<button onclick="open(this)">2</button>
<button onclick="open(this)">3</button>
</body>
</html>
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.
I want to show an image when I click on the button. But right now the button hides the image when I click on it. Is there a way to reverse this? This is the code I have.
var flag = 1;
function coursework() {
if (flag == 1) {
document.getElementsById("coursework").style.display = "none";
flag = 0;
} else {
document.getElementById("coursework").style.display = "block";
flag = 1;
}
}
<button onclick="coursework()">Show Coursework</button>
<div id="coursework">
<img src="Wellcome.png" width="300">
</div>
Thank you :)
You can set the image to display: none; initially and then change your if-else condition accordingly so that the image is displayed on first click and hide on second click and so on. Also, it should be getElementById and not getElementsById.
document.getElementById("coursework").style.display="none";
var flag =1;
function coursework() {
if(flag==1)
{
document.getElementById("coursework").style.display="block";
flag=0;
}
else{
document.getElementById("coursework").style.display="none";
flag=1;
}
}
<button onclick="coursework()">Show Coursework</button>
<div id="coursework">
<img src="https://images.pexels.com/photos/87840/daisy-pollen-flower-nature-87840.jpeg?auto=compress&cs=tinysrgb&h=350" width="300">
</div>
I am assume scenario that initially you hide image and when click on button it will show it, may be it will different from what you want and try to give this answer. Refer following code
<html>
<body>
<button onclick="show()">Show Coursework</button>
<div id="coursework" style="display:none">
<img src="welcome.png" width="300">
</div>
<script>
function show(){
document.getElementById("coursework").style.display="block";
}
</script>
</body>
</html>
hope this will help full.
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>
I have some code I'm working on that toggles a div of information depending on the user clicking an image. What I'm looking for is assistance in getting the image to swap when the user clicks, then to swap back when it's clicked again. The image should be changing to: https://casetest.blackboard.com/bbcswebdav/users/kas200/collapse.gif
I'm a newbie when it comes to coding with JS, so any help provided would be much appreciated!
<script type="text/javascript">
function toggleMe(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none"){
e.style.display="block";
}
else{
e.style.display="none";
}
return true;
}
</script>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para1')" value="Toggle"><br>
<div id="para1" style="display:none">
This is my text for section 1!
</div>
<br>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para2')" value="Toggle"><br>
<div id="para2" style="display:none">
This is my text for section 2!
</div>
<br>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para3')" value="Toggle"><br>
<span id="para3" style="display:none">
This is my text for section 3!
</span>
You've got the right idea. What I did for this case was add an id to each image with the name of the div + _img -- grabbed that element the same way, then updated the src:
javascript
function toggleMe(a){
var e=document.getElementById(a);
var i=document.getElementById(a+'_img');
if(!e)return true;
if(e.style.display=="none"){
i.src="https://casetest.blackboard.com/bbcswebdav/users/kas200/collapse.gif"
e.style.display="block"
}
else{
i.src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif"
e.style.display="none"
}
return true;
}
html
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para1')" value="Toggle" id="para1_img"><br>
<div id="para1" style="display:none">
This is my text for section 1!
</div>
<br>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para2')" value="Toggle" id="para2_img"><br>
<div id="para2" style="display:none">
This is my text for section 2!
</div>
<br>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para3')" value="Toggle" id="para3_img"><br>
<span id="para3" style="display:none">
This is my text for section 3!
</span>
here's a working example: http://jsfiddle.net/8h4T7/1/
PURE CSS
There's no need to use JS.
Here you go with a simple HTML / CSS solution:
LIVE DEMO
<input id="_1" class="toggler" type="checkbox">
<label for="_1"></label>
<div>This is my text for section 1!</div>
CSS:
.toggler,
.toggler + label + div{
display:none;
}
.toggler + label{
background: url(https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif);
position:relative;
display:inline-block;
width:11px;
height:11px;
}
.toggler:checked + label{
background: url(https://casetest.blackboard.com/bbcswebdav/users/kas200/collapse.gif);
}
.toggler:checked + label + div{
display: block;
}
The good part is that both your images are loaded in the browser so there won't happen an useless image request to the server (creating a time-gap) with no image visible (while it's loading).
As you can see the trick is to hide the checkbox and the div,
than using the :checked state you can do your tricks.
PURE JS
If you really want to play with JS than here's some changes to simplify the HTML markup:
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" value="para1"><br>
<div id="para1" style="display:none">This is my text for section 1!</div>
Note that I've changed the useless value to something useful, and removed the unnecessary ID from your inputs. Also, I've removed the messy HTML inline onclick callers. They're hard to maintain in production.
The input value will now help us to target your ID containers.
var imgSRC = "//casetest.blackboard.com/bbcswebdav/users/kas200/";
function toggleFn(){
var tog = this.tog = !this.tog;
var targetEl = document.getElementById(this.value);
targetEl.style.display = tog ? "block" : "none";
this.src = imgSRC + (tog?"collapse":"expand") + ".gif";
}
var $para = document.querySelectorAll("[value^=para]");
for(var i=0; i<$para.length; i++) $para[i].addEventListener('click', toggleFn, false);
LIVE DEMO 1
Another JS version:
var imgSRC = "//casetest.blackboard.com/bbcswebdav/users/kas200/";
function toggleFn(){
var el = document.getElementById(this.value);
el.style.display = el.style.display=='none' ? "block" : "none";
this.src = imgSRC +(this.src.match('expand') ? "collapse" : "expand")+ ".gif";
}
var $para = document.querySelectorAll("[value^=para]");
for(var i=0; i<$para.length; i++) $para[i].addEventListener('click', toggleFn, false);
LIVE DEMO 2
jQuery VERSION
Having the exact same as above HTML this is the needed jQuery code:
var imgSRC = "//casetest.blackboard.com/bbcswebdav/users/kas200/";
$(':image[value^="para"]').click(function(){
var tog = this.tog = !this.tog;
$('#'+ this.value).fadeToggle(); // or use .slideToggle();
this.src = imgSRC + (tog?"collapse":"expand") + ".gif";
});
LIVE DEMO
The interesting part of the code above is the way we store the current state directly into the this element reference Object:
var tog = thistog = !this.tog;
and using a set negation we create the toggle state.
Instead, if you're familiar with the bitwise XOR operator you can use it (to achieve the same) like:
var tog = this.t ^= 1;
XOR DEMO
Using jQuery
You can also use jQuery. It's a tool designed to help young coders. It allows manipulation of JavaScript through minimal functions.
Adding <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> to the head of your document will allow you to use jQuery. Then you can add some style to your collapsibles like this method based on pennstatephil's code.
function toggleMe(a){
var e=$('#'+a);
var i=$(a+'_img');
if(!e) return false;
if(e.css('display') == "none" ) {
i.attr('src', 'https://casetest.blackboard.com/bbcswebdav/users/kas200/collapse.gif');
e.fadeIn('slow');
}
else {
i.attr('src', 'https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif');
e.fadeOut('fast');
}
return true;
}
And an example can be seen here
jQuery API Documentation can be found here