I'm currently trying to insert text content that change depending of image validation using a single class for multiple divs. Any help is appreciate!
HTML
...
<div id="trophies"><img id="trophyimage" src="//user/trophies/A.png" height="100" width="100">
<span id="text-content" class="spaner"></span></div>
<div id="trophies"><img id="trophyimage" src="//user/trophies/B.png" height="100" width="100">
<span id="text-content" class="spaner"></span></div>
<div id="trophies"><img id="trophyimage" src="//user/trophies/C.png" height="100" width="100">
<span id="text-content" class="spaner"></span></div>
Right now using the next Javascript it's inserting the text content but it only does it once per ".spanner" class, not in the rest.
JavaScript
var trophy = document.getElementById("trophyimage");
if(trophy.src == "...//user/trophies/A.png"){
var x = document.getElementsByClassName("spaner")[0];
x.textContent = "Trophy A";
}
else if (trophy.src == "...//user/trophies/B.png"){
var x = document.getElementsByClassName("spaner")[0];
x.textContent = "Trophy B";
}
else{ var x = document.getElementsByClassName("spaner");
x.textContent = "Null";
}
I'm trying to figure out how to make it work using something like this:
JavaScript
var trophiestext = Array.from(document.querySelectorAll("spaner"));
trophiestext.forEach(function(troph) {
var trophy = document.getElementById("trophyimage");
if(trophy.src == "...//user/trophies/A.png"){
var x = document.getElementsByClassName("spaner");
x.textContent = "Trophy A";
}
else if (trophy.src == "...//user/trophies/B.png"){
var x = document.getElementsByClassName("spaner");
x.textContent = "Trophy B";
}
else{ var x = document.getElementsByClassName("spaner");
x.textContent = "Null";
}
}
Thanks in advance!
First off, there is a problem, multiple HTML elements cannot share the same id attribute, you must switch them for classes, also "//user/trophies/A.png" is probably not a valid directory
HTML:
<div class="trophies">
<img class="trophyimage" src="../user/trophies/A.png" height="100" width="100">
<span class="text-content spanner"></span>
</div>
<div class="trophies">
<img class="trophyimage" src="../user/trophies/B.png" height="100" width="100">
<span class="text-content spanner"></span>
</div>
<div class="trophies">
<img class="trophyimage" src="../user/trophies/C.png" height="100" width="100">
<span class="text-content spanner"></span>
</div>
Now, JavaScript can handle your HTML much better
Javascript:
// Don't forget the dot before the word trophies
const trophies = document.querySelectorAll('.trophies')
trophies.forEach(element => {
const img = element.querySelector('.trophyimage')
const src = img.getAttribute('src')
const span = element.querySelector('.spanner')
// change for the src to fit your files
if (src === '../user/trophies/A.png') span.innerText = 'Trophy A'
else if (src === '../user/trophies/B.png') span.innerText = 'Trophy B'
else span.innerText = 'Null' // Actually writes the word null, for no text use empty quotes
})
If you need more help, just reply to this answer :)
Use classes, add descriptions based on that and then add a generic description to those not found.
let trophyDesc = [{
name: "type-a",
description: "Trophy A"
}, {
name: "type-b",
description: "Trophy B"
}, {
name: "type-c",
description: "Trophy C"
}, {
name: "type-unknown",
description: "Trophy Grand"
}];
const result = trophyDesc.find(({
name
}) => name === 'type-unknown');
//console.log(result.description);
let trophies = document.getElementById("trophies");
let trophylist = trophies.getElementsByClassName("trophy");
//console.log(trophylist);
for (var i = 0, len = trophylist.length | 0; i < len; i = i + 1 | 0) {
let t = trophylist[i];
for (let d of trophyDesc) {
let hasClass = t.classList.contains(d.name);
if (hasClass) {
let e = t.querySelector(".trophy-text-content");
e.textContent = d.description;
t.classList.add('found');
break;
}
}
}
// now do not found ones
const f = trophies.querySelectorAll(`.trophy:not(.found)`);
for (let n of f) {
n.querySelector(`.trophy-text-content`).textContent = result.description;
}
console.log(f.length);
.trophyimage {
height: 100px;
width: 100px;
}
<div id="trophies">
<div class="trophy type-a"><img class="trophyimage" src="//user/trophies/A.png" alt="a">
<span class="trophy-text-content">A</span></div>
<div class="trophy type-b"><img id="trophyimage" src="//user/trophies/B.png" alt="b">
<span class="trophy-text-content">B</span></div>
<div class="trophy type-c"><img id="trophyimage" src="//user/trophies/C.png" alt="c">
<span class="trophy-text-content">C</span></div>
<div class="trophy type-u"><img id="trophyimage" src="//user/trophies/u.png" alt="u">
<span class="trophy-text-content">U</span></div>
</div>
Related
I am trying to create a changing text for every 3 seconds. But it seems just to run once and then it stops doing anything. My code:
HTML
<div class="output">
<h2>True Multi-Purpose Theme for
<span class="changingtext">Business</span>
and More
</h2>
</div>
JavaScript
let newText = document.querySelector('.changingtext')
setInterval(function() {
if (newText.innerHTML = 'Business'){
newText.innerHTML = 'Agencies';
}
else if (newText.innerHTML = "Agencies"){
newText.innerHTML = 'Startups';
}
else {
newText.innerHTML = 'Business';
}
}, 3000)
The problem is that you are using assignation instead of comparaison in your if
WRONG
if(newText.innerHTML = 'Business'){
CORRECT
if (newText.innerHTML === 'Business') {
let newText = document.querySelector('.changingtext')
setInterval(function() {
if (newText.innerHTML === 'Business') {
newText.innerHTML = 'Agencies';
} else if (newText.innerHTML === "Agencies") {
newText.innerHTML = 'Startups'
} else {
newText.innerHTML = 'Business'
}
}, 3000)
<div class="output">
<h2>True Multi-Purpose Theme
<be>
for
<span class="changingtext">Business</span> and More
</h2>
</div>
Also, the following could be better :
const text = document.querySelector('.changingtext')
const texts = [
'Business',
'Agencies',
'Startups',
];
function nextText() {
const actualTextIndex = texts.findIndex(x => text.innerText === x);
const newTextIndex = actualTextIndex + 1 === texts.length ? 0 : actualTextIndex + 1;
text.innerText = texts[newTextIndex];
}
setInterval(nextText, 3000)
<div class="output">
<h2>True Multi-Purpose Theme
<be>
for
<span class="changingtext">Business</span> and More
</h2>
</div>
You can improve it again by :
Creating an utility function that will work in standalone getting the selector, the time between a text change and the list of texts to loop from
Gl
I would like to use the addEventListener as a condition
so that if the condition is true by the clicking of the
image, the code executes, but it doesn't seem to work.
HTML
<div class = "content">
<img src = "dog.png" alt = "" id = "firstImage" >
<img src = "coatOfArm.png" alt = "" id = "second
Image" >
<p id = "score" >0</p>
</div>
JavaScript
var firstImage =
document.getElementById("firstImage");
var secondImage =
document.getElementById("secondImage");
var score= document.getElementById("score");
var totalScore_1 = 0;
var totalScore_2 = 0;
firstImage.addEventListeners("click",function() {
totalScore_1++;
score.innerHTML = totalScore_1;
})
secondImage.addEventListeners("click", function() {
totalScore_2++;
score.innerHTML = totalScore_2;
})
function increScore() {
if(first Image clicked == true){
firstImage. append(score) ;
} else{
secondImage. append(score) ;
}
} ;
increScore() ;
I am practicing with JavaScript Array function. What I want to achieve is to show google embedded images inside the display section when the user clicks "Show my grocery list" button after entering "banana", else the texts will be shown instead.
These are my codes.
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup",function(ev){
if(ev.keyCode == 13){
groceryList.push(grocery.value);
console.log("array",groceryList);
}
});
showItems.addEventListener("click",function(){
for (var i = 0; i < groceryList.length;i++){
if(groceryList[i] == "banana"){
display.src = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
#display {
width:100px;
height:100px;
}
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery"/>
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>
It is currently not showing anything. I have a feeling that I have written a wrong syntax inside the loop function? I would appreciate a solution and tips. Thank you.
You've to remove the keyCode=13 condition first and then need to create an img element with src of image based on condition (groceryList[i] == "banana") to display the image inside the <div> element, For example:
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup", function(ev) {
//if(ev.keyCode == 13){
groceryList.push(grocery.value);
//console.log("array",groceryList);
//}
});
showItems.addEventListener("click", function() {
for (var i = 0; i < groceryList.length; i++) {
if (groceryList[i] == "banana") {
var source = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
var img = document.createElement("IMG"); //create img element
img.src = source; //set img src
display.appendChild(img); // display image inside <div>
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery" />
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>
Wanting to use document.getElementById() to load images into HTML in Rails.
Section of HTML code
<div id="dealersCards">
<span id = "D0"></span>
<span id = "D1"></span>
<span id = "D2"></span>
<span id = "D3"></span>
<span id = "D4"></span>
<span id = "D5"></span>
<span id = "D6"></span>
<span id = "D7"></span>
</div>
Corresponding Javscript code
function displayPlayerOneInitialCards()
{
length = dealerCards.length;
for( dealerCount = 0; dealerCount < length; dealerCount++)
{
newCard = dealerCards[dealerCount]
if(dealerCount == 0)
{
var cardToDisplay = newCard.cardFaceDown;
}
if(dealerCount == 1)
{
var cardToDisplay = newCard.cardToDisplay;
}
dealerIdName = 'D';
dealerIdName = dealerIdName + dealerCount.toString();
fileNameCard= '<img width="80" height="128" src="images/'+ (cardToDisplay.trim())+'" alt="Card"/>';
document.getElementById(dealerIdName).innerHTML = fileNameCard;
}
}
Error message:
No route matches [GET] "/game/BlackJack/images/H3.gif"
images are in app/assets.
My ultimate goal is to get out the information my website. I am trying to get something like this returned:
{
Goals: {
1: 'ET6',
2: 'ET10'
},
Sub-Off: 80,
Sub-On: 'ET1'
}
so I have the following markup (the huge line breaks are necessary):
<span class="stats jamie">
<img src="/client/images/icon-ball.gif" alt="Goals" width="13" height="13">
ET:6,ET:10
<img src="/client/images/suboff.gif" alt="Sub-Off" width="13" height="13">
80
<img src="/client/images/subon.gif" alt="Sub-On" width="13" height="13">
ET:1
</span>
What I have so far
$('.jamie').find('img').each(function(index){
console.info($(this).attr('alt'));
});
var stats = {};
$('.jamie img').each(function(){
var name = $(this).attr('alt');
var data = $(this)[0].nextSibling // Get the next node
.nodeValue // Get its text value
.trim() // Remove the extra spaces
.toLowerCase() // to lower case
.replace(/:/g,'') // remove colons
.split(','); // split on commas
stats[name] = data; // add to object
});
console.log(stats);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="stats jamie">
<img src="/client/images/icon-ball.gif" alt="Goals" width="13" height="13">
ET:6,ET:10
<img src="/client/images/suboff.gif" alt="Sub-Off" width="13" height="13">
80
<img src="/client/images/subon.gif" alt="Sub-On" width="13" height="13">
ET:1
</span>
The accepted answer actually doesn't give you what you want. Here's an example using vanilla JS, jquery isn't needed to do a simple loop. This could be used if additional data is added you would just need to change the parent element and split the data with commas.
var parent = document.querySelectorAll('.stats img');
var obj = {};
for(var i in parent){
var img = parent[i];
var key = img.alt;
if(!img.nextSibling) break;
var values = img.nextSibling.data.trim().split(',');
if(values.length > 1){
obj[key] = {};
for(var c in values){
obj[key][c] = values[c];
}
} else{
obj[key] = values[0].toString();
}
}
console.log(obj)
a = {};
$('.jamie').find('img').each(function(){
var textVal = $.trim(this.nextSibling.nodeValue).replace(/:/,'').toLowerCase();
var textValArray = textVal.split(',');
var textValObj = {};
if( textValArray.length > 1 ){
$.map(textValArray , function( val, i ) {
textValObj[ i + 1 ] = val;
});
a[$(this).attr('alt')] = textValObj;
} else {
a[$(this).attr('alt')] = textVal;
}
});
console.log(a)
.spacer{height: 3000px; display: block; width: 100%;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<span class="stats jamie">
<img src="/client/images/icon-ball.gif" alt="Goals" width="13" height="13">
ET:6,ET:10
<img src="/client/images/suboff.gif" alt="Sub-Off" width="13" height="13">
80
<img src="/client/images/subon.gif" alt="Sub-On" width="13" height="13">
ET:1
</span>
We can only guess at the full parsing rules from the short example provided.
I expect you want something like this :
var obj = {};
$("span.stats img").each(function() {
var nextNode, key, val, text, arr;
nextNode = this.nextSibling;
if(nextNode.nodeType !== 3) { // test for text node
return true; // continue
}
key = $(this).attr('alt');
text = $.trim(nextNode);
arr = text.split(',');
if (arr.length < 2) {
val = text;
} else {
val = {};
for(var i=0; i<arr.length; i++ ) {
val[i] = arr[i].replace(':', '');
}
}
obj[key] = val;
});