I'm trying to get the name of the uploaded image file in my HTML. I tried to apply the solutions at https://stackoverflow.com/questions/1804745/get-the-filename-of-a-fileupload-in-a-document-through-javascript and https://stackoverflow.com/questions/14359913/how-to-get-value-of-img-tag. They helped me a bit but not fully.
So, my img tag looks just like this:
<img id="imgPreview" src="Anzeige%20erstellen-Dateien/default_offers_photo-edd8e5ff2d549a9fa1a898b23119931ebd0e745.png" width="500px" height="360px" style="padding-left:15px;" onload="imgListener()"/>
and the above function looks like this:
function imgListener(imgFile){
console.log(document.getElementById('imgPreview').src)
}
When I run this code it shows me a crazy long text with thousands of letters and digits. That's for sure not what I asked for.
The console output looks something like this, but only a lot longer:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QCCRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAABJADAAIAAAAUAAAAUJAEAAIAAAAUAAAAZJKRAAIAAAADOTYAAJKSSOKbCtSjAI9aS3sUX7ZQFxnirCgdqr27Dbip1/Sk79RD+dvWmHvTt+3jrTG57VSFsKqfXFWUT5elQx9hVlc7R6U7jG7h3pjSfhQ3XimbR6VK3F5H4wXGreZxuyAevWora+kLnDZH865Zb5+qYz0rd0rVo9PkR5og8IILNu5A9a8ajH2asz6nGTdaTmjrYLh/s+8pnIwQaba6lPExEVzcIwyQPNOB+HpW2lqsibVGCRnHUjIrPvPDc0vmJhUDcZDYNdu60PDhJRleR6docryafbST8TtGC47ZrWUjIz+FY9jMPJjDENhVA29sCrsc3Y1aMTQ3buN2B9aSEnec8L61XDU9WAI6n8aYiWSTDHAx60RsNu7OTUe4Z6U9JjH0XrQBu+GwrXBbrtHQ9vesXxhdLHrF/KyjFopz6kAZrd8OyBVnYYOFGc/WvPviVqS2vh/xXdyYUpayHcOAOMVEti42PHbbXLLxNcT5ljjui5OGGNwzxipVuNQ8PTCSBSIx29favEtF1i5t4oZHJkUg/wC8MnqDXpOgePEkjWG4DzRHgux5FYuLR18y5nY9Z8P+N7a/AjdmSVhkI/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97sq2MgkXa3NPuNJim+bZzVOwJWfFdZbW/mRAsKxkrbE9bHLNpSqpGzDdjVZdKkEnPArsZNPLdF/SnR6bu5K1jruW7pWObtdJZscYroNP08RYyOatra+T2prTbKrm01OflbJXxGKyrxutWJ7oMp5/Osi5vNxIzVxvciUVYnt5grAVkePLlP7NhjZsiSeJP++pFUj9auQyZauI+IOpz3niPw5olnk3FxqVmvy88GVW5HphSePT0yR7eFi3JR6ngYt2jO72R9p20flTGNT8i4C+wx0rSj7VUX5ZpOn3uKsxtz6160t7s+dWxbhkNSDO/NRQ/ezVnvVLQC5bsNvAqwuWqrbt/kj/vZwPrQIi/dRsGI8wdv/1ZqzayR+dGQm0E/Lt6Z496q/ZtvO75fUc0+EbpU2ncVIPp6dKAOtiX5Rk5qZfz9qhh/wBWueDjpUg6jnAqhEy7RwetKOmetR/dXrmnBg2c/lQALyeOlMumPk9eKMkn2z0qO8b9ycAdPWhgZh3bwe3erEP5+lZxT/SAykFgeVLE1oQt8oyMVIyfjjmnJwx5xTP0py/e5poTP//Z
I'm using src and not value. I'm guessing that's what's causing this. but i dont know how else I could access this information,I now know that value is not used for img tag. How can I do it, so that I get just the name of the file?
this works, just tested on a local file and give the correct name. just have to familiarize yourself with the object properties on the img object.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<img id="imgPreview" src="Anzeige%20erstellen-Dateien/default_offers_photo-edd8e5ff2d549a9fa1a898b23119931ebd0e745.png" width="500px" height="360px" style="padding-left:15px;" onload="imgListener()"/>
<script>
function imgListener(imgFile){
console.log(document.getElementById('imgPreview').attributes[1].textContent);
}
</script>
</html>
let me know if that works
alternative
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<img id="imgPreview" src="Anzeige%20erstellen-Dateien/default_offers_photo-edd8e5ff2d549a9fa1a898b23119931ebd0e745.png" width="500px" height="360px" style="padding-left:15px;" onload="imgListener()"/>
<script>
function imgListener(imgFile){
let name = document.getElementById('imgPreview').attributes[1].textContent;
let nameSplit = name.split("/");
let lastSplit = nameSplit[nameSplit.length - 1];
console.log(lastSplit);
}
</script>
</html>
Try something like this:
function imgListener(imgFile){
const el = document.getElementById('imgPreview');
const tmp = document.createElement("div");
tmp.appendChild(el);
console.log(tmp.getElementsByTagName("img")[0].getAttribute("src").split("/").reverse()[0])
}
<img id="imgPreview" src="Anzeige%20erstellen-Dateien/default_offers_photo-edd8e5ff2d549a9fa1a898b23119931ebd0e745.png" style="padding-left:15px;" onload="imgListener()"/>
Create a temporary item and append the image to get the attribute, I don't know if this works in your case.
document.getElemntById('whatever the ID is').files[0].name
Related
this is my js code
const imgSrcs = [
'C:\Users\obito\OneDrive\Desktop\To-Students\4.jpg',
'C:\Users\obito\OneDrive\Desktop\To-Students\5.jpg',
'C:\Users\obito\OneDrive\Desktop\To-Students\6.jpg'
];
const img = document.querySelector('img');
img.src =imgSrcs[Math.floor(Math.random() * imgSrcs.length)];
and this is my html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript: DOM</title>
<link rel="stylesheet" href="css5.css">
<script defer src="ex5.js"></script>
</head>
<body>
<figure id="header">
<img src="#" alt="#">
</figure>
</body>
</html>
i am trying to make this page everytime you reload it a random picture from the array pops up
this only worked for me if i try to link an image through a website url or somthing
but when i try to get images from my pc and use the folderpath to reach the image this never works
and i keep getting this msg in the console
tar5.html:1 Not allowed to load local resource: file:///C:/UsersobitoOneDriveDesktopTo-Students%06.jpg
any idea why this is happening?
Use relative path. If your html is in folder To-Students and your images in To-Students/images then use const imgSrcs = ['images/4.jpg', 'images/5.jpg', 'image/6.jpg']
remove the defer on your script and have
window.addEventListener("load",function() {
const img = document.querySelector('img');
img.src =imgSrcs[Math.floor(Math.random() * imgSrcs.length)];
})
I think It's because the javascript cannot access to C (because it needs that administrator accept the javascript)
why doesn't the commented statement work
HTML CODE:
<img class = "preview" alt = "Styling with a Bandana" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover = "upDate(this)">
JAVASCRIPT CODE:
function upDate(previewPic){
var x=document.getElementById('image');
//x.style.background="url(previewPic.src)";//why doesn't this work while the next statement works
x.style.background="url('"+previewPic.src"')";
}
Why are you using getElementbyId when your class doesn't have an id of image (at least in the sample you provided). Either add the id or select by the class or tag name
In your code "url(previewPic.src)" is full string that's why it doesn't work. Because your code doesn't know what's previewPic.src
If you want to use a variable inside a string you can use string concatenation or template string to do so. You can check my code.
You can check details about template literals from MDN_link
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<img onmouseover="upDate(this)" class="preview" alt="Styling with a Bandana" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" >
</body>
<script>
function upDate(previewPic){
console.log(previewPic.src);
previewPic.style.background=`url(${previewPic.src})`;
//x.style.background="url('"+previewPic.src"')";
}
</script>
</html>
Both of your examples do not work, the correct way of setting the background image of an HTML tag is to use
x.style.background = "url("+previewPic.src+")";
note the "+" sign after previewPic.src.
explanation:
First: "url(previewPic.src)"; this changes your previewPic.src into a string literal as its encapsulated in the quotation.
Second: x.style.background="url('"+previewPic.src"')"; this will not work as you're missing "+" sign after previewPic.src
further read MDN
I am working with HTML, CSS, jQuery, and JavaScript, all on one HTML page. Generally, I trying to figure out for the first time how to access information from the HTML body for use in my JavaScript code.
I want to set a variable in JavaScript equal to the string contained in the data attribute of one of my <div> elements.
Can I use document.getElementsByClassName()[] in my JavaScript to actually pull the information out of the HTML document? In examples on W3schools and elsewhere, I only see it used to change the value of some HTML element, not to actually use its input. Is there something more fundamental that I'm missing, here?
____here's my more specific code (where div.onlyOne is the only div of that class, and has the data-need attribute "string i need"):
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need")
Why will this not store "string i need" into myVar?
It works, make sure though, that you run the script after the markup or DOM load, or else the script will not find the element as it has not yet been loaded.
After in markup
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<div class="onlyOne" data-need="hey there"></div>
<script type="text/javascript">
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
</script>
</body>
</html>
DOM load
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
});
</script>
</head>
<body>
<div class="onlyOne" data-need="hey there"></div>
</body>
</html>
May I suggest you use document.querySelector('.onlyOne') instead in the future. With that you can narrow down the result list in a more efficient way.
Src: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
<div class="onlyOne" data-need="some text">...</div>
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
https://jsfiddle.net/howa6w1o/
since you are using jQuery, you can simplify your code to get the contents of the data-attribute: as follows:
$(document).ready(function(){
var myVar = $(".onlyOne").eq(0).data("need");
})
I have two separate files one with my html code and with my javaScript. What I am trying to do is create a function in javascript then call that function in the html. Both files are in the same folder along with the image. I'm new to both languages and to this site so please go easy;
I would really appreciate it if someone could help me please.`
JavaScript to load image below:
var menu = new image();
menu.src = "Fitness App Entry Scrren.jpg"
function menuScreen(){
document.getElementById("menu").getAttribute("src");
}
Html code to call function:
<!DOCTYPE html>
<html>
<head>
<body src="Functions.js">
<script onload="menuScreen()"></script>
</body>
<head>
</html>
What you are doing is against the rules of HTML. First of all, <body></body> should be outside of <head></head>. You should have <script></script> in either <head></head> or <body></body>. The <body> tag should have the onload attribute set to menuScreen(), and the <script> tag's src attribute should be set to Functions.js (as John Hascall said). By the way, John Hascall is right, there is no element with the ID of "menu" so it won't work unless you create a <div> or <iframe> with the specific ID and append the image to it in your Functions.js file.
So, your JavaScript code should look like this:
var menu = new Image(); // note that the constructor is capitalized
menu.src = "Fitness App Entry Screen.jpg";
// Create a <div> with the image within it.
var division = document.createElement("div");
division.setAttribute("id", "menu");
division.appendChild(menu);
document.body.appendChild(division);
function menuScreen() {
division.getAttribute("src"); // you can use division because it has the id of menu
}
And here is your HTML code to run the page (according to the HTML5 specifications, note that):
<!DOCTYPE html>
<html>
<head>
<script src="Functions.js"></script>
</head>
<body onload="menuScreen()">
<!-- Left intentionally blank -->
</body>
</html>
Hopefully this will help you!
I am trying to write a piece of code which replaces an image with another image on page load. But unfortunately it does not happen so. The second image does not load. i only see an icon with a cross mark after pageload. Please have a look at the below code and let me know what's wrong. Thanks in advance.
<html>
<head>
<script type="text/javascript">
function loadImage()
{
document.getElementById('ab').src ="C:\Users\Gagan\Desktop\green.png";
}
</script>
</head>
<body>
<img Id= "ab" src="C:\Users\Gagan\Desktop\red.jpg" onload="loadImage()">
</body>
</html>
In JavaScript, backslash is the escape character. If you want to include it in a string, you have to escape it using itself:
document.getElementById('ab').src = "C:\\Users\\Gagan\\Desktop\\green.png";
For future viewers of this question, I would recommend the unobtrusive JavaScript pattern for this, where the onload is done completely in JavaScript:
<html>
<head>
<script type="text/javascript">
var img = document.getElementById('ab');
function loadImage()
{
img.src ="C:\\Users\\Gagan\\Desktop\\green.png";
}
img.onload = loadImage;
</script>
</head>
<body>
<img id="ab" src="C:\Users\Gagan\Desktop\red.jpg" alt="" />
</body>
</html>