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!
Related
HTML.
<div id="listsalon">
<ul data-role="listview" data-inset="true" data-filter="true" >
</ul>
</div>
JS.
for (var i = 0; i < arr.length; i++) {
companyname = arr[i].CompanyName;
picture = arr[i].Picture;
address = arr[i].Address;
$("#listsalon ul").append("<li class='ui-corner-all'>" +
"<a id=" + '"' + "salon" + (i + 1) + '"' + "><img src='" + picture +
"'style='height:160px; width:200px;' class='ui-corner-all'>" +
"<h2 style='font-size:13px'>" + companyname + "</h2>" +
"<p style='font-size:10px'>" + address + "</p>" +
"</a></li>");
}
$("#salon1").bind("click", function () {
window.location = "salon.html"
});
Problem:
So first I pull data and put in 3 variables, companyname, picture and address. i have x sets of these data. i want to put in a list form. i am able to list out, but the function doesn't recognise the id and it does not work. please help. ty
This is because #salon1 element is being created dynamically. Moreover, .bind() in JQuery is deprecated. For such cases you should use .on()
$("#listsalon").on("click", "a#salon1", function () {
window.location = "salon.html"
});
More at jQuery click not working for dynamically created items
Proof of work
var arr = [{"CompanyName": "A", "Picture": "https://via.placeholder.com/140x100", "Address": 1}, {"CompanyName": "B", "Picture": "https://via.placeholder.com/140x100", "Address": 2}];
for (var i = 0; i < arr.length; i++) {
var companyname = arr[i].CompanyName;
var picture = arr[i].Picture;
var address = arr[i].Address;
$("#listsalon ul").append("<li class='ui-corner-all'>" +
"<a href='#' id=" + '"' + "salon" + (i + 1) + '"' + "><img src='" + picture +
"'style='height:160px; width:200px;' class='ui-corner-all'>" +
"<h2 style='font-size:13px'>" + companyname + "</h2>" +
"<p style='font-size:10px'>" + address + "</p>" +
"</a></li>");
$("#listsalon").on("click", "a#salon"+(i+1), function () {
alert("Redirecting...");
window.location = "salon.html"
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="listsalon">
<ul data-role="listview" data-inset="true" data-filter="true" ></ul>
</div>
To add event listeners to dynamically created objects, you need to create DOM objects using document.createElement. This lets you hold to the actual element even before appending it.
Then, you can use it like you would use any other object retrieved using a query string.
$(document).ready(function() {
let array = ["a", "b", "c"];
for (let i = 0; i < array.length; i++) {
let el = document.createElement('li');
$(el).html(array[i]);
$(el).on('click', function() {
alert('Click!');
});
$("#listsalon ul").append(el);
}
});
#listsalon ul li {
background-color: #eee;
padding: 0.5em;
margin-bottom: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="listsalon">
<ul data-role="listview" data-inset="true" data-filter="true" >
</ul>
</div>
CSS styles are just for clarity.
Here is a sample. .bind() in JQuery is deprecated. For such cases, you should use .on()
for (var i = 0; i < 5; i++) {
$("#listsalon ul").append("<li class='ui-corner-all'>" +
"<a id=" + '"' + "salon" + (i + 1) + '"' + ">"+(i + 1)+"</a></li>");
$("#salon"+(i + 1)).on("click", function () {
alert('clicked')
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="listsalon">
<ul>
</ul>
</div>
You were defining your click function outside for loop. That's why DOM didn't recognize your id
I need to load XML data to next and previous buttons on the popup box. When button click, my code is fail to load the XML data. How can I implement the code.
Here is the script
function xmlParser(xml){
xml = $(xml).children();
$(xml).children().each(function () {
let tag = $(this).prop("tagName");
let image = '<img style="background-image:url(' + $(this).find("image").text() + ')"' + '" />';
let image2 = '<div><img src="' + $(this).find("image").text() + '" width="100%" alt="' + '" />' + '</div>';
let head = '<div>' + $(this).find("head").text() + '</div>';
let html = `<div class="col-sm-4 random" id="random">
<a href="#${tag}" id="openModalBtn">
<div>${image}</div>
<h5>${head}</h5>
</a>
</div>`;
let popup = `<div id="${tag}" class="overlay">
<div class="popup">
‹
›
<h6>${head}</h6>
<a class="close" href="#">×</a>
<div>${image2}</div>
</div>
</div>`;
$("#xmldata").append(html);
$("#popup").append(popup);
});
}
Plunker
Firstly div id is being duplicated if you use directly tag name. So use index in for loop and do some simple calculation to get prev & next items, something like:
$(xml).children().each(function (idx) {
let tag = $(this).prop("tagName");
let nextIdx = idx + 1;
let prevIdx = idx - 1;
//to make cyclic rotation
nextIdx = nextIdx == total ? 0 : nextIdx;
prevIdx = prevIdx == -1 ? (total -1) : prevIdx;
//..........check plunker code
http://next.plnkr.co/edit/Sj188FthvFu6H5uv?open=lib%2Fscript.js
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.
In the following code, on the line commented "PROBLEM LINE", attr causes the console.log to print out "undefined" when you click on one of the s. I can't seem to figure out why:
test.js
var html = '';
// number of panels in the carousel
var panelCount = 0;
// panel that is to the forefront of the carousel
var currentPanel = 0;
$(document).ready(function(){
for (var i=0; i < 5; i++) {
html += '<div class="team-member" id="' + panelCount + '">' + panelCount + '</div>';
html += '<div class="reflection" id="' + panelCount + '"></div>';
panelCount++;
}
$('#carousel').html(html);
$(".container-carousel").on('click', '.team-member', function(e) {
var target = $(e.currentTarget);
var targetId = parseInt(target.attr('id'));
var frontRotation = currentPanel * (360/panelCount);
$("#" + targetId + ".reflection").css("transform", "rotateY( " + frontRotation + "deg ) translateZ( 288px ) translateY( 175px ) translateZ( 175px ) rotateX( 90deg )");
var targetIdString = '' + targetId;
/* PROBLEM LINE: */
$("#" + currentPanel + ".reflection").attr('id', targetId);
console.log($("#" + currentPanel + ".reflection").attr('id'));
$("#" + targetId + ".reflection").attr('id', currentPanel);
});
});
test.html
<!DOCTYPE html>
<!-- JQuery-->
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type = "text/javascript" src = "test.js"></script>
<section class="container-carousel">
<div id="carousel" style="transform: translateZ(-288px) rotateY(-360deg);"></div>
</section>
</html>
Any ideas why?
This is because immediately after you change the id of the element, you try logging by selecting with the old id.
$("#" + currentPanel + ".reflection").attr('id', targetId);
/*The id is now targetId*/
console.log($("#" + currentPanel + ".reflection").attr('id'));
/*currentPanel will not work because an element with that id no longer exists*/
Change your console.log to
console.log($("#" + targetId + ".reflection").attr('id'));
See it working here
The main problem in your code is, you have duplicate IDs in your page. So the id selector will always fetch the first element with the id, the tries to apply the .refelection class selector which does not match thus your selector $("#" + currentPanel + ".reflection") does not return any result.
So use 2 different ids for the team-member and reflection elements, I think you can use a suffix as shown below for 1 element
for (var i = 0; i < 5; i++) {
html += '<div class="team-member" id="' + panelCount + '">' + panelCount + '</div>';
html += '<div class="reflection" id="' + panelCount + '-reflection"></div>';
panelCount++;
}
then
$("#" + targetId + "-reflection").css("transform", "rotateY( " + frontRotation + "deg ) translateZ( 288px ) translateY( 175px ) translateZ( 175px ) rotateX( 90deg )");
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
I have a JavaScript function that loops through classes and gets an ID which I have wrapped in a div called 'item'. Once they click on a button it bubbles up through the div which I have wrapped information in and collected the ID. For Example:
output = "<div id='item" + json_output[i].id + "'>" +
"<div class = 'itemBoxes'>"+
"<h3 class ='itemTitle'>" +json_output[i].classname + "</h3>" +
"<div class = 'paddingBottom'></div>" +
"<p class = 'itemDesc'>" + json_output[i].classdescription + '</p>' +
"<div class ='itemInfo'>" +
"<div class ='bookingItems'> <img src = 'img/glyphicons-268-credit-card.png'</img> <p class = 'itemDetails'>£" + json_output[i].classprice + "</p></div> "+
"<div class ='bookingItems'> <img src = 'img/glyphicons-46-calendar.png'</img> <p class = 'itemDetails'>" + json_output[i].classdate + "</p></div>" +
"<div class ='bookingItems'> <img src = 'img/glyphicons-55-clock.png'</img><p class = 'itemDetails'>"+ json_output[i].classstarttime +"</p></div>" +
"<div class ='bookingItems'> <img src = 'img/glyphicons-44-group.png'</img><p class = 'itemDetails'>" + json_output[i].classparticipants + " spaces </p></div>" +
"</div>" +
"<p id ='bookingBox'> <input type='button' class='bookingSubmit' value='Book Now'/> </p>" +
"</div>" +
"</div>";
target.innerHTML += output;
The code I use to find the ID is:
var fetchModifyButton;
//Gets the button that says 'Modify'
fetchModifyButton = _c("bookingSubmit");
//Remove Button.
for (var i = 0, j = fetchModifyButton.length; i < j; i++) {
fetchModifyButton[i].addEventListener("click", function () {
var e, productID, newID;
//Bubbles up and finds the ID of the product they want to modify
e = event.target;
while (e.id.indexOf('item') == -1) {
e = e.parentNode;
}
productID = e.id;
//Removes everything but the numbers.
newID = productID.replace(/[^0-9.]/g, "");
getClassInfoForBooking(newID, newID);
});
}
This works perfectly in Google Chrome, IE11, and most other browsers.
It doesn't work in IE8,9 or 10.
The error message I get in is:
SCRIPT5007: Unable to get property 'id' of undefinded or null reference
Then it points to the line: while (e.id.indexOf('item') == -1) {
I wondered if anyone had any ideas why?
use event.srcElement for IE
var addEvent = window.addEventListener||window.attachEvent;
fetchModifyButton[i].addEvent("click", function () {
var e, productID, newID;
//Bubbles up and finds the ID of the product they want to modify
e = event.target||event.srcElement;
while (e.id.indexOf('item') == -1) {
e = e.parentNode;
}
productID = e.id;
//Removes everything but the numbers.
newID = productID.replace(/[^0-9.]/g, "");
getClassInfoForBooking(newID, newID);
});