display images array onclick button - javascript

HTML: I set the button onclick "myFunction" Now I would like images to be displayed onclick
<body>
<p>Click the button to see some images</p>
<button onclick="myFunction()">See the Images!!!</button>
<script src="js2/images.js">
</script>
</body>
JS: Need to display images onclick...Not sure if i am on the right track as I am a beginner at JS...I cant seem to get the images to display, only the src name of the images....
function myFunction() {
pge = new Array ()
pge[4] = "../images/sky3.jpg"
pge[3] = "../images/sky8.jpg"
pge[2] = "../images/sky7.jpg"
pge[5] = "../images/sky6.jpg"
pge[0] = "../images/sky5.jpg"
pge[1]= "../images/sky4.jpg"
pge[6] = "../images/sky1.jpg"
pge[7] = "../images/sky2.jpg"
for (i=0;i<=pge.length-1;i++) {
var img = document.createElement("img");
????????
}
}

Add line
img.setAttribute("src", pge[i]);
in your ?????? part

Something like this should do the trick. (in part based on How to display image with javascript?)
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<p>Click the button to see some images</p>
<button onclick="myFunction()">See the Images!!!</button>
<script>
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
function myFunction() {
var pge = ["http://www.w3schools.com/graphics/pic_the_scream.jpg", "http://www.w3schools.com/images/colorpicker.gif"];
for(var i = 0; i < pge.length; i++){
show_image(pge[i], 100, 200, i)
}
}
</script>
</body>
</html

Your HTML needs a place to display the images when the button is clicked. You can use CSS to style the div.
<body>
<p>Click the button to see some images</p>
<button onclick="myFunction()">See the Images!!!</button>
<div id="showImg"></div>
<script src="js2/images.js"></script>
</body>
You don’t have to use the Array constructor. Store your images in an array as shown below, use a for-loop to loop through the array, then use the innerHTML property to create img tags, locate your images and display them. You can use CSS to style the images.
var pge = ["sky3.jpg", "sky8.jpg", "sky7.jpg", "sky6.jpg", "sky5.jpg", "sky4.jpg", "sky1.jpg", "sky2.jpg"];
var showImg = document.getElementById("showImg");
var myFunction = function(){
for(var i = 0; i < pge.length; i++)
{
showImg.innerHTML = "<img src='images/" + pge[0] + "'/> <img src='images/" + pge[1] + "'/> <img src='images/" + pge[2] + "'/> <img src='images/" + pge[3] + "'/> <img src='images/" + pge[4] + "'/> <img src='images/" + pge[5] + "'/> <img src='images/" + pge[6] + "'/> <img src='images/" + pge[7] + "'/>";
}
}

Related

JavaScript error while assigning a value to script tag src attribute

I am trying to add a word in my between by src using JavaScript, by getting that word from another div element. Running it results in the following error:
Cannot set property 'src' of null`
Here's my code:
<html><head></head><body>
<div id='content'></div>
<script>
function handleResponse(response) {
var post_number = Object.keys(response.items).length; //number of posts
for (i=0; i<post_number; i++) {
document.getElementById("content").innerHTML += "<div class='posts'><h1>" + response.items[i].title + "</h1>" + response.items[i].content + '</div>';
}
}
</script>
<div id='myImg'>Lists</div>
<script id='demo' src=""></script>
<script>
var x = document.getElementById("myImg").innerHTML;
var y= document.getElementById("demo"); y.src="https://www.googleapis.com/blogger/v3/blogs/5039479718685240371/posts?labels="+x+"&callback=handleResponse&key=AIzaSyDxfWmXTRnO5yIp25NvuUEBWKSa_5mqjHA";
</script>
</body>
</html>
Try This:
<script>
var x = document.getElementById("myImg").innerHTML;
var s = document.createElement( 'script' );
s.setAttribute('src', "https://www.googleapis.com/blogger/v3/blogs/5039479718685240371/posts?labels=" + x + "&callback=handleResponse&key=AIzaSyDxfWmXTRnO5yIp25NvuUEBWKSa_5mqjHA");
document.body.appendChild(s);
</script>

select element with class and id with jquery

I'm trying to select two different elements with class and id, the first works but the second doesn't (it works without the id), I can't figure out why.
help me, please.
code:
$(document).ready(function() {
var num = 0;
$("#add").click(function() {
$("main").append("<div class=\"card\" style=\"width: 20rem;\">\
<div class=\"card-block\">\
<h4 class=\"card-title\" id=\"" + num.toString() + "\"></h4>\
<p class=\"card-text\" id=\"" + num.toString() + "\"></p>\
</div>\
</div>");
var title = $("#noteTitle").val();
var body = $("#noteBody").val();
var photo = $("#notePhoto").val();
if (photo) {
$(".card").prepend("<img class=\"card-img-top\" src=" + photo + " alt=\"Card Image\">");
}
$(".card-title#"+ num.toString()).html(title);
$(".card-text#"+ num.toString()).html(body); //<-- here is where I get the problem
num ++;
});
})
Here you go with the solution . https://jsfiddle.net/0knefedh/
$(document).ready(function() {
var num = 0;
$("#add").click(function() {
$("body").append("<div class=\"card\" style=\"width: 20rem;\">\
<div class=\"card-block\">\
<h4 class=\"card-title\" id=\"title" + num.toString() + "\"></h4>\
<p class=\"card-text\" id=\"text" + num.toString() + "\"></p>\
</div>\
</div>");
var title = "dasdasd";
var body = "asdasdas";
var photo = $("#notePhoto").val();
if (photo) {
$(".card").prepend("<img class=\"card-img-top\" src=" + photo + " alt=\"Card Image\">");
}
$(".card-title#title"+ num.toString()).html(title);
console.log(num);
$(".card-text#text"+ num.toString()).html(body); //<-- here is where I get the problem
num ++;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit" id="add" value="Add" >Add</button>
Problem is with ID that you are generating for .card-title and .card-body. Both are having same ID, where as ID should be unique.
So, it work for the first time then it didn't.

HTML - JavaScript - Adding and Deleting/Hiding Elements

In my website the user is going to select an image, that image will then be inserted into a div tag. I need it so when the user clicks the image that was inserted into the div then it will be removed (deleted or hidden) from the div. I've tried:
document.getElementById("elementId").style.display = "none";
and other similar things. I really just cant get this to work please help!
HTML + JavaScript code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<script>
var cardNumber = 1;
var deck = [];
var addCard = function(cardName)
{
if("undefined" != document.getElementById("card" + cardNumber).value)
{
if(deck.indexOf(cardName) > -1)
{
}
else
{
if(deck.length != 1)
{
deck.push(cardName);
document.getElementById("card" + cardNumber).innerHTML = '<img id = "' + cardName + '" class = "deckCardSize" onclick = updateCards(' + cardName + ') src = "Images/Cards/' + cardName + '.png">';
cardNumber += 1;
}
if(deck.length >= 1)
{
cardNumber = 1;
}
}
}
}
</script>
</head>
<body>
<div id = "card1" class = "cards"></div>
<div id = "1">
<img class = "cardSize" onclick = "addCard('Archer')" src = "Images/Cards/Archer.png">
</div>
</body>
CSS Code:
.cards
{
height:150px;
width:125px;
float:left;
margin-left:6.2%;
margin-bottom:30px;
border:5px solid #ff6666;
background-color:#ff6666;
}
.cardSize
{
height:150px;
width:125px;
float:left;
margin-left:7%;
margin-top:30px;
}
You can delete the img by id.
Also fix the issue with the updateCards function:
document.getElementById("card" + cardNumber).innerHTML = '<img id = "' + cardName + '" class = "deckCardSize" onclick = "updateCards(\'' + cardName + '\')" src = "' + cardName + '.png">';
For example,
<div id="card1" class="cards">
<img id="Archer" class="deckCardSize" onclick="updateCards('Archer')" src="Archer.png">
</div>
Then just remove the div with id="Archer":
document.getElementById("Archer").remove();
FYI, I added a simple updateCards function that just hides the img instead of removing it entirely :
var updateCards = function(cardName) {
document.getElementById(cardName).style.display = 'none';
}
You need to attach a click event listener to a class that is applied to all inserted images. the function that the listener fires would then apply css.style.display = "none" to this
First, remove all spaces between attributes and its values (I mean everywhere in your code), that is:
<div id="card1" class="cards"></div><!-- correct -->
<div id = "card1" class = "cards"></div><!-- incorrect -->
Second, you have an error in your code here:
document.getElementById("card" + cardNumber).innerHTML = '<img id = "' + cardName + '" class = "deckCardSize" onclick = updateCards(' + cardName + ') src = "Images/Cards/' + cardName + '.png">';
You have missed double quotes around onclick's value. Replace it with this:
document.getElementById("card" + cardNumber).innerHTML = '<img id="' + cardName + '" class="deckCardSize" onclick="updateCards(' + cardName + ')" src="Images/Cards/' + cardName + '.png">';
Also, you have to define function updateCards(name), it maybe empty, but it must exists. If it doesn't exists, than any javascript code will stops running after you clicked on that image.
Third, <div id = "1"> has an error too. id attribute must starts from a letter.
here is working code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<script>
var cardNumber = 1;
var deck = [];
function addCard(cardName) {
if ("undefined" != document.getElementById("card" + cardNumber).value) {
if (deck.indexOf(cardName) > -1) {
} else {
if (deck.length != 1) {
deck.push(cardName);
document.getElementById("card" + cardNumber).innerHTML = '<img id="img' + cardName + '" class="deckCardSize" onclick="updateCards(\'' + cardName + '\')" src="Images/Cards/' + cardName + '.png">';
cardNumber += 1;
}
if (deck.length >= 1) {
cardNumber = 1;
}
}
}
}
function updateCards(cardName) {
//some work
document.getElementById("img" + cardName).remove();
}
</script>
</head>
<body>
<div id="card1" class="cards"></div>
<div id="main1">
<img class="cardSize" onclick="addCard('Archer')" src="Images/Cards/Archer.png">
</div>
</body>
Tested and worked!

html image src call javaScript variable

this is my code: I want to ask
<script type="text/javascript">
var total = 4;
</script>
How can I do this?
<img src="img/apple_" + total + ".png" id="imageBox"/>
I've been try to use call function and document.onload but it's not work at all, can somebody save me?
I am supposing you just want to update the image src with javascript.
document.getElementById('imageBox').src = "img/apple_" + total + ".png";
You need to add html in JavaScript like this:
<div id="foo"></div>
<script type="text/javascript">
var total = 4;
document.getElementById('foo').innerHTML = '<img src="img/apple_' + total + '.png" id="imageBox"/>';
</script>
window.onload = function() {
var total = 4;
document.getElementById('imageBox').src = 'img/apple_' + total + '.png"';
};
<img src="" id="imageBox"/>
Here is a clean way to do this.
Demo
var create_img_element = function(total, targetId){
//create the img element
var img = document.createElement('img');
//set the source of the image
img.src = 'img/apple_' + total + '.png';
//add the image to a specific element
document.getElementById(targetId).appendChild(img);
}
create_img_element(5, 'foo');

javascript to iterate image folders and add images to an unordered list

I am trying to figure out exactly why this script wont work. I first thought it might be because of the div and the following ul, but it still wont work after assigning an additional ID to the ul. Really need to figure this out tonight, so all help is highly appreciated.
HTML
<div id="Home-Image">
<h1>Images</h1>
<ul id="Home-Images">
<li><img src="" width=100 height=100/></li>
<li><img src="" width=100 height=100/></li>
<li><img src="" width=100 height=100/></li>
<li><img src="" width=100 height=100/></li>
<button id="toggle-two">View more Images</button>
</ul>
JavaScript
$(document).ready(function() {
var files = {'jpg':4};
var pageName = "d";
for (var ext in files){
for (var i = 0; i < files[ext]; i++){
var src = "../Images/D/allimages" + pageName + "-" + (i+1) + "." + ext;}
var img = new Image();
img.src = src;
var container = document.getElementById('Home-Images');
container.appendChild(img);
}});
Maybe you want something like this
$(document).ready(function() {
var files = {'jpg':4}, pageName = "d", container = $('#Home-Images');
for (var ext in files)
{
for (var i = 0; i < files[ext]; i++)
{
var src = "../Images/D/allimages" + pageName + "-" + (i+1) + "."+ext ;
var img = $('<img src="'+src+'" width=100 height=100 />');
container.append($('<li/>').html($('<a/>', {'href':'#'}).html(img)));
}
}
});
But make sure this path http://yourDomain/Images/D/allimagesd-1.jpg ​is right for all images.
Here is a demo but images are not available but you can see the source by browser inspection tool.
Modified code:jsfiddle
HTML:
<div id="Home-Image">
<h1>Images</h1>
<ul id="Home-Images">
<button id="toggle-two">View more Images</button>
</ul>​
JS:
$(document).ready(function() {
var files = {'jpg':4};
var pageName = "d";
var html = "", src;
for (var ext in files){
for (var i = 0; i < files[ext]; i++){
src = "../Images/D/allimages" + pageName + "-" + (i+1) + "." + ext;
html += '<li><img src="'+ src +'" width=100 height=100/></li>';
}
$("#Home-Images").prepend(html );
}}); ​

Categories