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.
Related
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>
When I remove a file that I uploaded, I got a error. That is js:42 Uncaught TypeError: Cannot read property 'removeChild' of null. I have to use removeChild and var for IE. Is there a good way to fix the error?
html
<form action="" enctype="multipart/form-data" class="page_form">
<label class="ui_upload upload_label" for="upload-doc">
<input type="file" name="file" id="upload-doc"
accept=".pdf,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
multiple />
<span class="btn sm label upload_btn">upload file</span>
</label>
<div class="upload_documents_wrap visually_hide">
<div class="upload_documents"> </div>
</div>
<div class="visually_hide" id="upload-file">
<div class="upload_info shadow light upload_file">
<span class="tit sm file_name"> </span>
<span class="tit sm file_size"> </span>
<button class="file_remove" type="button">Remove</button>
</div>
</div>
<button type="submit" class="btn sm">submit</button>
</form>
js
(function () {
var formElement = document.querySelector(".page_form");
var fileChooserEl = formElement.querySelector('.upload_label input[type="file"]');
var uploadDocumentsWrap = formElement.querySelector(".upload_documents_wrap");
var uploadDocuments = uploadDocumentsWrap.querySelector(".upload_documents");
var templateItemParent = document.querySelector("#upload-file");
var templateItem = templateItemParent.querySelector(".upload_file");
var uploadFiles = [];
var myFileList = [];
var onFileChooserChange = function () {
for (var i = 0; i < fileChooserEl.files.length; i++) {
var position = templateItem.cloneNode(true);
var uploadFileName = position.querySelector(".file_name");
var uploadFileSize = position.querySelector(".file_size");
var uploadFileRemove = position.querySelector(".file_remove");
var fileName = fileChooserEl.files[i].name.toLowerCase();
uploadDocumentsWrap.classList.remove("visually_hide");
uploadFileName.textContent = fileName; // file size
var suffix = "bytes";
var size = fileChooserEl.files[i].size;
if (size >= 1024 && size < 1024000) {
suffix = "KB";
size = Math.round(size / 1024 * 100) / 100;
} else if (size >= 1024000) {
suffix = "MB";
size = Math.round(size / 1024000 * 100) / 100;
}
uploadFileSize.textContent = size + suffix;
uploadFileRemove.addEventListener("click", function (evt) {
evt.preventDefault();
myFileList = myFileList.filter(function (item) {
return item.name.toLowerCase() !== uploadFileRemove.previousElementSibling.textContent;
});
console.log(myFileList);
var index = uploadFiles.indexOf(evt.target.parentNode);
uploadFileRemove.parentNode.parentNode.removeChild(uploadFileRemove.parentNode);
uploadFiles.splice(index, 1);
myFileList.splice(index, 1);
console.log(index);
if (!uploadFiles.length) {
uploadDocumentsWrap.classList.add("visually_hide");
}
});
uploadDocuments.appendChild(position);
uploadFiles.push(position);
myFileList.push(fileChooserEl.files[i]);
}
fileChooserEl.value = "";
};
console.log(uploadFiles);
var getFormData = function () {
var data = new FormData(formElement);
for (var i = 0; i < myFileList.length; i += 1) {
data.append(fileChooserEl.name, myFileList[i]);
}
return data;
};
fileChooserEl.addEventListener("change", onFileChooserChange);
})();
The error is on this line:
uploadFileRemove.parentNode.parentNode.removeChild(uploadFileRemove.parentNode);
I debugged the code and find that you removed wrong file every time when clicking the "Remove" button. It's easier and more clear to identify which file to remove using index. I edit the code like this and it works well:
...
var index = uploadFiles.indexOf(evt.target.parentNode);
//edit
var removefile = document.querySelectorAll(".upload_info")[index];
uploadDocuments.removeChild(removefile);
//uploadFileRemove.parentNode.parentNode.removeChild(uploadFileRemove.parentNode);
uploadFiles.splice(index, 1);
myFileList.splice(index, 1);
console.log(index);
...
Result:
So I currently have slider that the user can dynamically fill upon uploading images. I'm using bootstrap for the slider which requires the first slide to have the class "active" in order to work, however when I try to assign that class to the first slide using
"if ($("#carousel-inner").find('li')) {
var slide1 = document.getElementById("slide-0");
slide1.setAttribute ("class", "active");
}
it doesn't recognize the slide id and assigns null to the value, returning "cannot setAttribute of null".
Any advice?
HTML
<div id="slideshow-container">
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<ul class="carousel-inner" id ="carousel-inner">
</ul>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
JS
window.onload = function() {
$('#_uploadImages').click(function () {
$('#_imagesInput').click();
setTimeout(activeness(), 5000)
});
$('#_imagesInput').on('change', function () {
handleFileSelect();
});
}
function handleFileSelect() {
//Check File API support
if (window.File && window.FileList && window.FileReader) {
var files = event.target.files; //FileList object
var output = document.getElementById("carousel-inner");
var arrFilesCount = [];
var start = $(output).find('li').length;
var end = start+ files.length;
var nonImgCount = 0;
var slide1 = document.getElementById("slide1")
var display = document.getElementById("displayImg")
for (var i = start; i < end; i++) {
arrFilesCount.push(i); // push to array
}
if(start !== 0){
$(output).find('li > nav > a.prev').first().attr('href','#slide-' + (end-1));
$(output).find('li > nav > a.next').last().attr('href','#slide-'+start);
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
//Only pics
if (!file.type.match('image')) {nonImgCount++; continue;}
var picReader = new FileReader();
picReader.addEventListener("load", function (event) {
var picFile = event.target;
current_i = arrFilesCount.shift();
if (current_i === 0) {
prev_i = files.length - 1; //This is for the first element. The previous slide will be the last image. (i=length-1)
} else {
prev_i = current_i - 1;
}
if (arrFilesCount.length - nonImgCount === 0) {
next_i = 0;
} else {
next_i = current_i + 1; //This is for the last element. The next slide will be the first image (i=0)
}
display.src = picFile.result
output.innerHTML = output.innerHTML + '<li id="slide-' + current_i + '" class="carousel-item">' + "<img class='d-block w-100' src='" + picFile.result + "'" + "title=''/>" + '</li>'; // TODO: Enter Title
});
//Read the image
picReader.readAsDataURL(file);
}
if ($("#carousel-inner").find('li')) {
var slide1 = document.getElementById("slide-0");
slide1.setAttribute ("class", "active");
}
} else {
console.log("Your browser does not support File API");
}
}
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 have a div with spans inside. They have data-item attr. How to find div with the biggest data-item attr. They are numbers starting from 0. For example I have:
<div class="wrapper">
<span data-num="0">text</span>
<span data-num="1">text</span>
<span data-num="2">text</span>
<span data-num="3">text</span>
</div>
Updated: This is part of my code, it's about uploading files and one of the input fields is multiple. And I show in a div with separate spans image names of the files. Use should add multiple files so I need to find the biggest data-num and increment it for the next file.
function getFiles(document, window, index) {
var inputs = document.querySelectorAll( '.app-file' );
input.addEventListener( 'change', function( e )
{
var fileName = '';
var num = 0;
if( this.files && this.files.length > 1 || $(this).next().next().html()) {
var fileName = [];
for (var i = 0; i < this.files.length; ++i) {
fileName.push(this.files.item(i).name);
var comma = '';
if($(this).next().next().html()) {
comma = ',';
}
divName.innerHTML = divName.innerHTML + comma + '<span class="image_name" data-num="'+num+'">' + this.files.item(i).name + '</span><span class="glyphicon glyphicon-remove remove-file" data-toggle="tooltip" data-placement="top" title="Remove"></span>';
num++;
}
} else {
fileName = e.target.value.split('\\').pop();
divName.innerHTML = '<span class="image_wrapper"><span class="image_name" data-num="'+num+'">' +fileName + '</span><span class="glyphicon glyphicon-remove remove-file" data-toggle="tooltip" data-placement="top" title="Remove"></span></span>';
var maxIndexItem = $.makeArray($('#wrapper [data-num]')).reduce(function(result, item) {
return $(item).data('num') > $(result).data('num') ? $(item) : result;
});
alert(maxIndexItem.text());
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="file-name" data-input="corporate_document" id="corporates"></div>
HTML
<div class="wrapper">
<span data-num="0">text1</span>
<span data-num="1">text2</span>
<span data-num="2">text3</span>
<span data-num="3">text4</span>
<span>text5</span>
<span data-num="">text6</span>
</div>
JS
$(document).ready(function(){
var arr = [];
$(".wrapper span").each(function(){
var dataNum = $(this).data("num");
if (dataNum != null) {
arr.push(dataNum);
}
}).promise().done( function(){
var max = Math.max.apply(Math, arr);
alert( $(".wrapper").find("[data-num=" + max + "]").text());
} );
});
Refer Fiddle
I think this code can helps you:
var maxIndexItem = $.makeArray($('.wrapper [data-num]')).reduce(function(result, item) {
return $(item).data('num') > $(result).data('num') ? $(item) : result;
});
alert(maxIndexItem.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
<span data-num="0">text 0</span>
<span data-num="1">text 1</span>
<span data-num="2">text 2</span>
<span data-num="3">text 3</span>
</div>