Arguments in js function - javascript

I have a table with 3 columns that show cards back, like this, so when a I press on card, an alert show me his number, but I don't know how show the number, I tried with href and onClick but I haven't success
The html
<table id="gallery">
</table>
<script>generateTable3col();</script>
The js
function generateTable3col(){
var cards = [5,1,8,3,2,4,6];
var rows = cards.length/3;
var columns = 3;
var rowNode, columnNode, link, img;
var table = document.getElementById("gallery")
var image = "backcard.png"
for (var r=0;r<rows;r++){
rowNode = document.createElement("tr");
rowNode.style = "width:33%;";
table.appendChild(rowNode);
for(var c=0;c<columns; c++){
columnNode =document.createElement("td");
columnNode = table.appendChild(columnNode);
link = document.createElement("a");
link.setAttribute("hideNumber", cards[1*r+c]);
//here I don't know how do
link.href = "javascript:showCard(this)" //this is window object
link.onclick = showCard(this); //execute when call the loop not when click
img = document.createElement("img");
img.style = "width: 100%;"
img.src = image;
link.appendChild(img);
columnNode.appendChild(link);
}
}
}
//How?
function showCard(element){
alert("card is: " + element.getAttribute("hideNumber")); //element is object window, not <a> element
}

Instead of this line:
link.onclick = showCard(this);
Use this:
link.onclick = function() { showCard(this); };
The difference here is that in the first case, showCard(this); is executed right away. While in the second case, you're assigning a function to onclick that will only get executed once the click occurs.

Related

Img src is undefined after addEventListener

I want to change a picture to a gif on mouse over, and revert it back on mouse out. But img src stays undefined after onmouseout, howerer it should be visible, because imgsrc array is an global varriable
Here is my code:
var list = document.querySelectorAll('span[data-oe-id] img');
var i;
var imgsrc=[];
for(i=0;i<3;i++)
{
imgsrc[i] = list[i].src;
list[i].addEventListener("mouseover",function(event)
{
console.log(imgsrc[i]); // Here it is undefined
this.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
});
list[i].addEventListener("mouseout",function(event)
{
this.src=imgsrc[i]; // Here is the same thing
});
}
Because let is brackes scope, better code will be :
var list = document.querySelectorAll('span[data-oe-id] img');
for(let i=0; i<list.length; i++){
let image = list[i];
let src = image.src;
image.addEventListener("mouseover",function(event){
console.log(src);
image.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
});
image.addEventListener("mouseout",function(event){
image.src=src;
});
}
Check it out and let me know.
The problem that you are having is with this. Within an event listener, this represents the event not the object calling the event.
Change this.src to list[i].src
this.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
to
list[i].src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
change
this.src=imgsrc[i];
to
list[i].src=imgsrc[i];

Load var n from localStorage and loop n times

I'm trying to learn JS and this is my little app.
Every time I press the "INSTANTIATE" button, it instantiates a tomatoe.png in my <div>.
When the user reloads the page, the tomatoe.png should appear as many times as they've pressed the "INSTANTIATE" button.
This is the code. For this purpose, I created a variable (i), and it increments on every button press.
I planned to save this variable into localStorage, and when the page gets reloaded, I want to call a loop function that instantiates the tomatoe.png i times.
function popUp() {
var img = document.createElement("img");
img.src = "tomato.png";
var src = document.getElementById("header");
src.appendChild(img);
i++;
localStorage.setItem("apples", i);
}
<button onclick="popUp()">INSTANTIATE</button>
<div id="header"></div>
So, when the user reloads the page, as many tomatoes should appear as many times they've pressed the button.
I think I have to use a loop, but I don't know how.
Just get the item in localStorage and loop until it reaches 0, creating a new image each time (localStorage don't works in StackOverflow snippets here because of security reasons, but you get the point).
var i = 0;
function popUp() {
newImage();
i++;
localStorage.setItem("apples", i);
}
function newImage() {
var img = document.createElement("img");
img.src = "tomato.png";
var src = document.getElementById("header");
src.appendChild(img);
}
var oldi = Number(localStorage.getItem("apples"));
while (oldi > 0) {
oldi--;
newImage();
}
<button onclick="popUp()">INSTANTIATE</button>
<div id="header"></div>
First of all, you have to declare i outside your function (in case you haven't done it already) and give it a value of zero, if it isn't exist in the Local Storage:
let i = localStorage.getItem("apples") || 0;
Then, create a loop, that loops i times:
for(let n = 0; n < i; n++){}
And finally, just create tomatoes:
const img = document.createElement("img");
img.src = "tomato.png";
const src = document.getElementById("header");
src.appendChild(img);
So, the full code should look like this:
document.addEventListener('DOMContentLoaded', function(){
function popUp() {
createTomato()
i++;
localStorage.setItem("apples", i);
}
function createTomato() {
const img = document.createElement("img");
img.src = "tomato.png";
const src = document.getElementById("header");
src.appendChild(img);
}
document.getElementById("instantiate").addEventListener("click", popUp)
let i = localStorage.getItem("apples") || 0;
for (let n = 0; n < i; n++) createTomato();
})
<button id="instantiate">INSTANTIATE</button>
<div id="header"></div>
Try it on codepen.io

Assigning an event function to many elements with pure Javascript

I'm building a table of links containing images with a javascript function. Here's the code:
function populateGrid(dataArray) {
var table = document.createElement("table");
table.id = "data-table";
var row = document.createElement("tr");
for (var i = 1; i <= dataArray.length; i++) {
var tableItem = document.createElement("td");
var linkContainer = document.createElement("a");
var itemImage = document.createElement("img");
linkContainer.href = dataArray[i - 1].url;
linkContainer.target = "_blank";
itemImage.onmouseover = function(e) {
linkHover(e);
};
itemImage.onmouseout = function(e) {
linkBlur(e);
};
itemImage.src = dataArray[i - 1].logo;
linkContainer.appendChild(itemImage);
tableItem.appendChild(linkContainer);
row.appendChild(tableItem);
// This checks to see if it's time to make a new row, in order to keep the table a square
if (i % Math.round(Math.sqrt(dataArray.length + 1)) === 0) {
table.appendChild(row);
row = document.createElement("tr");
}
}
table.appendChild(row);
document.getElementById('inject').appendChild(table);
}
I'm having issues with assigning the "onmouseover" and "onmouseout" events to each individual table item. Lint is telling me that it's bad form to assign functions within a for-loop, and it definitely seems messy to me. I've tried this:
itemImage.onmouseover = linkHover(e);
But when I do it this way, I get the error: "Uncaught ReferenceError: e is not defined". I need some context as to which element is causing the linkHover and linkBlur functions to be called, as I change the border of the corresponding image as seen in this .gif:
(I don't have enough reputation to post images, so here's the link: http://i.imgur.com/6r8rQQp.gifv)
My linkHover and linkBlur functions are as follows:
function linkHover(e) {
e.target.className = "green-border";
}
function linkBlur(e) {
e.target.className = "";
}
My question is: how should I do this better? I'm sure there must be a cleaner way that doesn't give lint errors.
Thanks in advance for your help.
EDIT:
Okay, so following gcampbell's advice, I'm assigning the event listener to the table like so:
var table = document.createElement("table");
table.onmouseover = function(e) {
linkHover(e);
};
table.onmouseout = function(e) {
linkBlur(e);
};
And then I check to make sure the target was an img:
function linkHover(e) {
if (e.target.tagName == "IMG") {
e.target.className = "green-border";
}
}
Is this bad form? Should I just condense these functions into the event assignments?
Thanks.

How to get the img id for dynamically building IMG tags based on click like Share or Like or Comment

Good Evening Everyone.
Background: I am getting list of images from a Mongo Database and then I am calling ajax once to load those data in to particular div.
Here I am building those img tags dynamically and then appending it to a div.
Now I am trying to get the img id based on user operation, lets say clicks on 'share button' for a particular img, then I have to get the image id, and then have to look search the DB with that image id.
My code after the ajax call is:
function showImages(imageList) {
for ( var i = 0, len = imageList.length; i < len; i++) {
var elem = document.createElement("img");
elem.src = 'getImg/' + imageList[i][0] + '/' + imageList[i][1];
elem.id = imageList[i][2];
alert(elem.id);
elem.height = '100';
elem.width = '100';
elem.alt = 'SPF HYD';
/* $("a[id=shareImage]").click(function(){
var qwerty = $("img", $(this).parent()).attr("id");
alert('image id is after anchor by click...'+qwerty);
}); */
var image = document.getElementById("imageLoad");
image.appendChild(elem);
}
}
Could any one help me to get the image id onclick or any button trigger?
I threw a quick demo together to demonstrate what I meant. It's made possible using jQuery event Delagation
function showImages(imageList) {
for ( var i = 0, len = imageList.length; i < len; i++) {
var elem = document.createElement("img");
elem.src = 'getImg/' + imageList[i][0] + '/' + imageList[i][1];
elem.id = imageList[i][2];
console.log(elem.id);
elem.height = '100';
elem.width = '100';
elem.alt = 'SPF HYD';
var image = document.getElementById("imageLoad");
image.appendChild(elem);
}
}
//The event handler is registered on the document object - the second argument here is the delegate, <img>
$(document).on("click", "img", function(e) {
alert($(this).attr("id"));
});
var imageList = [[0, 1, 2], [3, 4, 5]]; //These values are merely for testing
showImages(imageList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imageLoad"></div>
Using Event Delegation is necessary here because your img tags are being dynamically generated, plus it's a lot cleaner to register one event handler for all img tags, rather than an event handler for each
Hope this helps
Use addEventListener function to add an Event Listener to your dynamically created element.
var div = document.getElementById("div");
var imgShare = document.createElement("img");
imgShare.src = "http://icons.iconarchive.com/icons/graphicloads/100-flat-2/128/share-2-icon.png";
imgShare.id = "post002";
imgShare.addEventListener("click", share);
div.appendChild(imgShare);
var imgLike = document.createElement("img");
imgLike.src = "http://www.brandsoftheworld.com/sites/default/files/styles/logo-thumbnail/public/102011/like_icon.png?itok=nkurUMlZ";
imgLike.id = "post001";
imgLike.addEventListener("click", like);
div.appendChild(imgLike);
function share(e){
alert("Share id:" + e.currentTarget.id);
}
function like(e){
alert("like id:" + e.currentTarget.id);
}
<div id="div"></div>
JSFiddle Link...

I get an error on trying to get the img.src from my Html textfield

The following is my function that is called on click of a button.
The goal is to get the text value entered by the user and use it as an image source and finally display the image on the html body.
function ButtonClick() {
var link = document.createElement("a");
// create an image element.
var MyImg = document.createElement("img");
var MyImg.src = document.getElementById("textfield").value;
// append it to a list of elements.
link.appendChild(MyImg);
// append the newly added image to the html page body.
document.body.appendChild(link);
// clear textfield for next image src.
document.getElementById("textfield").value = "";
}
The error I receive is on line#7: "var MyImg.src = document.getElementById("textfield").value;"
SyntaxError: missing ; before statement example.js:19
*edited code after the fist suggestion.
MyImg.src = document.getElementById("textfield").value;
you should define variable once,
change
var MyImg = document.createElement("img");
var MyImg.src = document.getElementById("textfield").value;
to
var MyImg = document.createElement("img");
MyImg.src = document.getElementById("textfield").value;

Categories

Resources