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>
Related
I want to make a page to upload the avatar.
By default, I use the vector to show where the image will appear
and then provide a button to upload the URL to change the avatar.
That's all it is! But the script still doesn't work.
Pleased to hear your feedback on how to fix it. Bless
<img id="put_image_here_bitch" src="https://cdn0.iconfinder.com/data/icons/finance-vol-2-4/48/77-512.png" alt="" width="100px" height="100px">
<div class="block" > The person who uploads this is cool
</div>
<button onclick="hideElement()">Click to upload photo by URL</button>
<div>
<input id="input" autofocus class='hidden_element' style="display: none;" type="text" id="input">
</div>
<div>
<button class='hidden_element' style="display: none;" onclick="uploadImage()">UPLOAD</button>
</div>
This is my script
function hideElement(){
var hide = document.getElementsByClassName('hidden_element');
if (hide.style.display === "none") {
hide.style.display = "block";
} else {
hide.style.display = "none";
}
}
var uploadImage = function(){
image = document.getElementById('input').value;
showImage = document.getElementById('put_image_here_bitch').setAttribute('src', image);
};
As stated in the comments, .getElementsByClassName() returns a collection of elements, not a single element and your code attempts to call the style property of the collection, which doesn't exist.
Instead, you need to loop through the collection and operate on the elements within the collection individually, but don't use .getElementsByClassName() and instead use .querySelectorAll().
var hidden = document.querySelectorAll('.hidden_element');
function hideElement(){
// Loop over the colleciton elements
hidden.forEach(function(element){
if (element.style.display === "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
});
}
var uploadImage = function(){
image = document.getElementById('input').value;
showImage = document.getElementById('put_image_here_bitch').setAttribute('src', image);
};
<img id="put_image_here_bitch" src="https://cdn0.iconfinder.com/data/icons/finance-vol-2-4/48/77-512.png" alt="" width="100px" height="100px">
<div class="block" > The person who uploads this is cool
</div>
<button onclick="hideElement()">Click to upload photo by URL</button>
<div>
<input id="input" autofocus class='hidden_element' style="display: none;" type="text" id="input">
</div>
<div>
<button class='hidden_element' style="display: none;" onclick="uploadImage()">UPLOAD</button>
</div>
But, beyond that, you should also avoid using inline styles as they are the most specific way of setting a style and therefore the hardest to override. They also often require duplicated code to be written. Instead, use CSS classes as shown below:
// Get references to the DOM elements that you'll need to work with
const btnUpload = document.querySelector("button"); // find the first button
const hidden = document.querySelectorAll(".hidden");
const upload = document.querySelector(".upload");
// Do your event binding in JavaScript, not in HTML
btnUpload.addEventListener("click", hideElement);
upload.addEventListener("click", uploadImage);
function hideElement(){
// Loop over the collection of hidden elements
hidden.forEach(function(item){
// See how much more simple it is to work with classes?
item.classList.toggle("hidden");
});
}
function uploadImage(){
showImage = document.getElementById('put_image_here_bitch').setAttribute('src', input.value);
};
.hidden { display:none; }
<img id="put_image_here_bitch" src="https://cdn0.iconfinder.com/data/icons/finance-vol-2-4/48/77-512.png" alt="" width="100px" height="100px">
<div class="block" > The person who uploads this is cool
</div>
<button>Click to upload photo by URL</button>
<div>
<input id="input" autofocus class='hidden' type="text" id="input">
</div>
<div>
<button class='hidden upload'>UPLOAD</button>
</div>
simple.. getElementsByClassName() returns an HTMLCollection with all DOM elements containing that class. An HTMLCollection is like an array ( but not really ) containing element references.
thus you need to define which entry in the array you want to handle ( even if there's only one )
your code should work by simply adding [0] to your DOM read ( the '0' means the first element in the collection )
ex:
var hide = document.getElementsByClassName('hidden_element')[0];
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');
I'm supposed to add script to an HTML file so that when I click the first star in the star rating system, it will change the src to 'star-on.png' as opposed to 'star-off.png'. That, I can do. But I can't figure out how to make it so that if the user clicks the second star, it will change the src for both the first and the second star to 'star-on.png'.
Here's the code that my teacher provided:
<!-- 1. PUT YOUR NAME IN THIS COMMENT -->
<html>
<head>
<!-- 2. DO NOT EDIT THE CSS -->
<style type="text/css">
body {
margin: 0;
}
div {
width: 520px;
display: block;
margin-left: auto;
margin-right: auto;
}
img {
width: 100px;
}
</style>
<!-- 2.5 YOU MAY ALTER THE STYLING OF THE BUTTON IF YOU WISH. -->
<style type="text/css">
button {
width: 200px;
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<!-- 3. DO NOT ALTER THE HTML EXCEPT TO ADD ONCLICK, ONLOAD, AND SIMILAR ATTRIBUTES -->
<!-- AS NEEDED -->
<body>
<div>
<img src="star-off.png" id="one" class="2">
<img src="star-off.png" id="two" class="2">
<img src="star-off.png" id="three">
<img src="star-off.png" id="four">
<img src="star-off.png" id="five">
</div>
<button id="reset" onclick="document.getElementById('one').src='star-off.png'">Reset</button>
<!-- 4. YOU MAY PUT YOUR SCRIPTING HERE -->
<script>
document.getElementById('one').onclick = function () {
document.getElementById('one').src="star-on.png";
}
document.getElementById('two').onclick = function () {
document.getElementById('two').src="star-on.png";
}
document.getElementById('three').onclick = function () {
document.getElementById('three').src="star-on.png";
}
document.getElementById('four').onclick = function () {
document.getElementById('four').src="star-on.png";
}
document.getElementById('five').onclick = function () {
document.getElementById('five').src="star-on.png";
}
</script>
</body>
</html>
Except for the things inside the script tag and the onclick inside of the button, it's all my teacher's code.
This is what it looks like:
Well, you've really got most of what you're trying to do in your script already. Look at each of these lines:
document.getElementById('one').onclick = function () {
document.getElementById('one').src="star-on.png";
}
document.getElementById('two').onclick = function () {
document.getElementById('two').src="star-on.png";
}
document.getElementById('three').onclick = function () {
document.getElementById('three').src="star-on.png";
}
document.getElementById('four').onclick = function () {
document.getElementById('four').src="star-on.png";
}
document.getElementById('five').onclick = function () {
document.getElementById('five').src="star-on.png";
}
Essentially, each one is saying select the element by its Id attribute, identified in the preceding group by the 'id=""' in this part:
<img src="star-off.png" id="one" class="2">
<img src="star-off.png" id="two" class="2">
<img src="star-off.png" id="three">
<img src="star-off.png" id="four">
<img src="star-off.png" id="five">
and then attach an onclick event to it. When that onclick event fires, do the function that you've defined to the right of each of the equal signs following the event specification.
Inside each of your functions, it is simply going to identify the element on the DOM that matches the element id you're providing (just as you already did to assign the event handler in the previous section) and you're going to change the value for its 'src' attribute to the string you're defining on the right side of the equals.
Take the second one, per your request. Here's the HTML you're referencing (for both the first and second stars):
<img src="star-off.png" id="one" class="2">
<img src="star-off.png" id="two" class="2">
And here is the event handler you've already got in place for the second one:
document.getElementById('two').onclick = function () {
document.getElementById('two').src="star-on.png";
}
Right now if you click on that second star, you're only changing the src attribute of the element with an ID of 'two' to the 'star-on.png' image. So, if you want to also change the element of the star before it, it's got an ID of 'one', so you'll need to add this line within the event handler.
document.getElementById('one').src = "star-on.png";
Sure, there are more efficient ways to do this, but undoubtedly you'll learn about them as your course progresses. Here's what your event handler will look like with this update:
document.getElementById('two').onclick = function () {
document.getElementById('two').src="star-on.png";
document.getElementById('one').src = "star-on.png";
}
Please help me. I want to do the below activity in javascript programming with the help of "for loop".
Suppose there are five images on the web page. When I rollover the 1st image, the text should display "it's a first image". When I rollover the 2nd image, the text should display "it's a second image". When I rollover the 3rd image, the text should display it's a third image.
I have tried and it's successful but it's manual. I am new in Javascript programming..
<!DOCTYPE html>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<link rel="stylesheet" href="style_latest.css" type="text/css">
<title>MATHERAN TRIP</title>
<style>
#displayText
{
width:413px;
height:auto;
background-color:#666666;
color:white;
}
#displayText1
{
padding-left:5px;
}
</style>
</head>
<body>
<img src="images/img1.jpg" id="img1" onmouseover="clickEvent1()" onmouseout="imgRollout()" width="100" height="100">
<img src="images/img2.jpg" id="img2" onmouseover="clickEvent2()" onmouseout="imgRollout()" width="100" height="100">
<img src="images/img3.jpg" id="img3" onmouseover="clickEvent3()" onmouseout="imgRollout()" width="100" height="100">
<img src="images/img4.jpg" id="img4" onmouseover="clickEvent4()" onmouseout="imgRollout()" width="100" height="100"><br/>
<div id="displayText">
<span id="displayText1"></span>
</div>
<script>
var myData=new Array("Hi, How r u?", "Hey, whats up? Hey, whats up? Hey, whats up? Hey, whats up? Hey, whats up? Hey, whats up?", "Hello, whats going on?", "Hi friends")
document.getElementById("displayText").style.visibility='hidden';
function clickEvent1()
{
document.getElementById("displayText1").innerHTML=myData[0];
document.getElementById("displayText").style.visibility='visible';
}
function clickEvent2()
{
document.getElementById("displayText1").innerHTML=myData[1];
document.getElementById("displayText").style.visibility='visible';
}
function clickEvent3()
{
document.getElementById("displayText1").innerHTML=myData[2];
document.getElementById("displayText").style.visibility='visible';
}
function clickEvent4()
{
document.getElementById("displayText1").innerHTML=myData[3];
document.getElementById("displayText").style.visibility='visible';
}
function imgRollout()
{
document.getElementById("displayText").style.visibility='hidden';
}
</script>
</body>
</html>
I would recommend you don't include inline event attributes at each element. But I would consider including an inline html5 data- attribute with the message associated with the elements:
<img src="images/img1.jpg" data-msg="Hi, How r u?" width="100" height="100">
<!-- etc -->
Then you can bind the same rollover functions to each element using a loop as follows:
function doMouseOver(e) {
document.getElementById("displayText1").innerHTML =
e.target.getAttribute("data-msg");
document.getElementById("displayText").style.visibility='visible';
}
function doMouseOut() {
document.getElementById("displayText").style.visibility='hidden';
}
var imgs = document.getElementsByTagName("img"),
i;
for (i = 0; i < imgs.length; i++) {
imgs[i].addEventListener("mouseover", doMouseOver);
imgs[i].addEventListener("mouseout", doMouseOut);
}
Within the doMouseOver() function, the e argument is the event object, and thus e.target gives you a reference to the element the event happened to - so then you can retrieve the particular data-msg value for that element to display it.
Demo: http://jsfiddle.net/3c7Rb/
Having said that, you don't need the loop either. You can bind the functions directly to the document, and then within the mouse over handler you simply test whether the target element has the msg-data attribute. If it does, display it, otherwise do nothing:
function doMouseOver(e) {
var msg = e.target.getAttribute("data-msg");
if (msg) {
document.getElementById("displayText1").innerHTML= msg;
document.getElementById("displayText").style.visibility='visible';
}
}
function doMouseOut() {
document.getElementById("displayText").style.visibility='hidden';
}
document.addEventListener("mouseover", doMouseOver);
document.addEventListener("mouseout", doMouseOut);
Demo: http://jsfiddle.net/3c7Rb/1/
I printed to the screen 16 icons (little pictures).
Now I want to be able to select icons,
and when I press a button the selected icons ids will be sent in a form.
I saw in the net only checkboxes and lists multiselect,
what's the best way to do this?
(I'm pretty new to web design)
thanks ahead!
Although jQuery isn't in your tags, you should introduce yourself to jQuery. It'll make your life easier, for what you're trying to do. Here is the basic steps both if you use jQuery and if use just Javascript:
With jQuery
Give all your icons a class and each one a unique id:
<img src='icon1.png' data-iconID=2233 class='myIcons' />).
Then bind that class to a click event
$('.myIcons').bind('click', function() {
$(this).toggleClass('selectIcon');
});
Attach form submit function to onsubmit:
<form ... onsubmit="submitForm();">
Build submitForm function:
function submitForm() {
var csvIconIds = '';
$.each($('.myIcons.selectIcon'), function (index, value) {
csvIconIds += $(value).attr('data-iconID');
});
//submit scvIconIds here along with other form data (ajax?)
}
With Javascript
Similar as above but way more complicated...
To toggle classes see this thread: How to add/remove a class in JavaScript?
To getting attributes by class see this site: http://www.actiononline.biz/web/code/how-to-getelementsbyclass-in-javascript-the-code/
This could be a way using just plain Javascript or jQuery. I prefer the jQuery version, since it separates the click handler from the markup, instead of using inline onclick handlers, which are in general discouraged.
What this does is use an input element array, which you can create by adding [] to the element name. This same technique can be used on SELECTs and other elements, since it signals to the server that an array has been submitted, as opposed to value known by a single key.
<html>
<head>
<style type="text/css">
div img {
cursor: pointer;
border: 1px solid #f00;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script>
function setFormImage(id) {
if (id != '' && !document.getElementById('input_'+id)) {
var img = document.createElement('input');
img.type = 'text';
img.id = 'input_'+id;
img.name = 'images[]';
img.value = id;
document.imageSubmit.appendChild(img);
}
}
$(document).ready(function(){
$('#jqueryimages img').click(function(){
setFormImage(this.id);
});
});
</script>
</head>
<body>
<pre><?php
if (count($_GET['images'])) {
print_r($_GET['images']);
}
?></pre>
<div style="float: left; width: 49%;">
<h1>Plain ol' HTML</h1>
1. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-1" onclick="setFormImage(this.id)"/>
<br/>
2. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-2" onclick="setFormImage(this.id)"/>
<br/>
3. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-3" onclick="setFormImage(this.id)"/>
<br/>
4. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-4" onclick="setFormImage(this.id)"/>
</div>
<div id="jqueryimages" style="float: left; width: 49%;">
<h1>jQuery</h1>
5. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-5"/>
<br/>
6. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-6"/>
<br/>
7. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-7"/>
<br/>
8. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-8"/>
</div>
<h1>Form Submit</h1>
<form name="imageSubmit" method="get">
<input type="submit" value="View Selected"/>
</form>
</body>
</html>
try this
var idArray = [];
$("#container-id img").each(function(index,value){
idArray.push($(value).attr("id"));
});
//do anything with the array