how to change the background image using javascript and keyword this - 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

Related

How to add css styles to document.write in javascript

Hello I'm very new to javascript and doing my first steps I was wondering if I could style the content of a variable in the document.write instruction and I came to this.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.style1{
background-color: chartreuse;
}
</style>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var name1;
name1=prompt("Write your name");
document.write('<p class="style1">'+name1+'</p>');
</script>
</body>
</html>
I got that solved by reviewing some posts here the question is how does this actually work?
document.write('<p class="style1">'+name1+'</p>');
I'm not sure I understand why I need to put ' for this instruction could somebody explain that please thank you btw I'm sorry this is a very basic question but I would like to know also if you guys have some more ways to style a document.write it would be nice to know .
I'd suggest taking a slightly different approach. You can add a div to your HTML with an ID of "test" (or whatever you'd like), then edit the innerHTML of that div like so:
document.getElementById("test").innerHTML = name1;
document.write : Write HTML elements with text directly to the HTML document
var name1;
name1=prompt("Write your name");
document.write('<p class="style1">'+name1+'</p>');
Create a variable named name1
Give a value to name1 variable from user input in prompt alert
Write p element with class style1 and its content is value from name1 to HTML document
document.write(); is writing a text in your HTML File.
so if you write like this:
<script>document.write("<p>blah</p>");</script>
then you are writing html Source like <p>blah</p>.

How to get the name of an image file in my HTML

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+8pnIwQaba6lP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NWP7SX+9+tHMYex7F+6jSQEHmua1bQxIrGPr6VptqC92qKa+DcA5qZNM6KcZR2PMtW02eOVgRXN3mjXNwSMfSvWtQtDctnbmqUegtJICUrK19jv52keXWfgG4u5l8wKEJ5xyTXofhbwPbaKqsIlL45OK6qy0ZYVHy81otAI1xjFdSi0ck5uTs2ZrW4AwBUtrGAw4p7KQalgTJFQo6j0SNGCMFRWrprGJhWZCCuK0LdtuK76S5Ty63vJo2rpjJDgGuQ8SYht23/d9feuth+eGuO8dWxuLMxrLsJ549a6K9nC5zYO3tVFnx/4+sR9u1OSSL/XXTFG9gSP515lcQGNuOK9q+IluxmYSEB4yc7TnJY5zXlWoW3yse9ePypn0k97sq2MgkXa3NPuNJim+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

JavaScript Replace function giving out errors

I want this code to replace all ':)'s with my smiley emoji. Although when I run the code I get Uncaught TypeError: Cannot read property 'replace' of undefined at ?v=0.02:10 any help would be greatly appreciated!
Code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>SVG Emoji</title>
</head>
<body>
<script>
var html = document.getElementsByTagName("html").innerHTML;
html.replace(":)", "<img src='https://csf30816.github.io/svg-emoji/emojis/smile.svg'>");
document.getElementsByTagName("html").innerHTML = html;
</script>
<h1>:) Test</h1>
</body>
</html>
Replace
document.getElementsByTagName("html").innerHTML
with
document.getElementsByTagName("html")[0].innerHTML
as getElementsByTagName returns an array.
Also, the string.replace() method returns a new string without mutating / modifying the given one. You would need to re-assign the returned string to html = html.replace(...).
Also, you need to move your <script> to the bottom. Otherwise it can't access DOM elements that appear beneath it in your HTML document, such as the <h1> element:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>SVG Emoji</title>
</head>
<body>
<h1>:) Test</h1>
<script>
var html = document.getElementsByTagName("html")[0].innerHTML;
html = html.replace(":)", "<img src='https://csf30816.github.io/svg-emoji/emojis/smile.svg'>");
document.getElementsByTagName("html")[0].innerHTML = html;
</script>
</body>
</html>
See also How to get the <html> tag HTML with JavaScript / jQuery?
For a more robust approach to replacing text within the DOM see jQuery replace all occurrences of a string in an html page
Your code and the problem you are trying to solve are doing different things. This will give you the solution you are seeking, i.e. replace all ':)'s with my smiley emoji
function replaceTextByImage(pattern, src) {
document.body.innerHTML = document.body.innerHTML.replace(
new RegExp(pattern, 'g'),
'<span style="background-size: 100% 100%; background-image: url(\'' + src + '\');">&nbsp&nbsp&nbsp&nbsp</span>'
);
}
replaceTextByImage(':\\)', 'https://csf30816.github.io/svg-emoji/emojis/smile.svg');
replaceTextByImage(':P', 'https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/svg/1f61b.svg');
replaceTextByImage(':D', 'https://what.thedailywtf.com/plugins/nodebb-plugin-emoji-one/static/images/1f603.svg');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<p>
Hello World! How are you? :). Do you like this emoji :)
</p>
<div style="font-size:50px;">How about now :)</div>
<div style="font-size:25px">You can also do this :P and this :D now!</div>
</body>
</html>
PROS
Emoji will resize according to font used.
Replaces all occurrences of a pattern
CONS
If you have an inline script in the body of your html, it may be re-executed every time the function replaceTextByImage is called because it is setting the body's innerHTML.
If you want to use jquery then don't read this answer.
But for those who can allow their script not be jquery,
Here is your code.
document.getElementsByTagName("H1")[0].innerHTML = '<img src="https://csf30816.github.io/svg-emoji/emojis/smile.svg">';
<h1>:) Test</h1>
What the problem is:
You are returning an array.
Use one element with [0]:
document.getElementsByTagName("html")[0].innerHTML = html;

javascript click a button and create an image in a div

I've searched this problem of mine and found some solutions but there is something wrong I must be doing because it doesn't work.
I would like to, simply, just press a button and make an image appear in a certain div. Later, I'd like to add more buttons and each button will correspond to an image changing this image in the same div.
My code is this:
<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
</style>
</head>
<body>
<button id="button1">Button 1</button><button id="button2">Button 2</button></br>
<button id="button3">Button 3</button><button id="button4">Button 2</button></br>
<p> </p>
<div id="1"></div>
<div id="2"></div>
<script type="text/javascript">
document.getElementById("button1").onclick=function() {
document.getElementById("1").appendChild="<img id="image1" src="img/image1.png" />;
}
document.getElementById("button2").onclick=function() {
document.getElementById("1").appendChild="<img id="image2" src="img/image2.png" />;
}
document.getElementById("button3").onclick=function() {
document.getElementById("2").appendChild="<img id="image3" src="img/image3.png" />;
}
document.getElementById("button2").onclick=function() {
document.getElementById("2").appendChild="<img id="image4" src="img/image4.png" />;
}
</script>
</body>
</html>
but somehow I cannot make this work.
You're using double quotes inside a string encapsulated by double quotes:
"<img id="image1" src="img/image1.png" />;
This needs to be
"<img id=\"image1\" src=\"img/image1.png\" />";
Since JavaScript uses quotes (single or double) to set strings you need to escape quotes inside a string with \ to avoid breaking the string. In your original code JavaScript is parsing the string, finds the end of the string at id= and breaks because it expects a line terminator ; or a +.
Look at the highlighting in the first and second code block. It's all red in the second indicating a correct escaped string.
ALSO
appendChild only works with nodes/elements and not with strings. You need innerHTML, however that will overwrite the content of your div every time. If you don't want that you could use: insertAdjacentHTML()
Example:
document.getElementById("1").insertAdjacentHTML("beforeend", "<img id=\"image1\" src=\"img/image1.png\" />");
Try this:
Javascript:
document.getElementById(<img id>).src = "<link to img>";
HTML:
<img id='<img id>' src='<link to img>'>

How to unescape with javascript and translate with Google?

i have some code, when i input some test to text box and click Tranlate it will translate to English:
<html>
<head>
<style type="text/css">
input {font-size:12px; width:600px;}
</style>
<title>Translate</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div class="translate"></p>
<div class="translate_control" lang="en">
<input id="text1" class="translate"/>
<script>
function googleSectionalElementInit() {
new google.translate.SectionalElement({
sectionalNodeClassName: 'translate',
controlNodeClassName: 'translate_control',
background: '#f4fa58'
}, 'google_sectional_element');
}
</script>
<script src="http://translate.google.com/translate_a/element.js?cb=googleSectionalElementInit&ug=section&hl=en"></script>
</body>
</html>
http://jsfiddle.net/4CXGf/
Now, i want input some code to text1 as: \u83B7\u53D6\u9875\u9762 and i want when i click Translate it will auto unescape() with javascript "\u83B7\u53D6\u9875\u9762" to 获取页面 and auto translate to English with Google translate and show to text1. How to do it?
Sorry about my English!
There may be a shorter way to do this, but one option is to use the JSON predefined class to handle all the escaping. encodeURI/decodeURI sound like the most obvious approach, but neither of them work in the direction you're trying for, which is to take a string literal that actually says "\u83B7\u53D6\u9875\u9762", including literal backslashes. What you want is to essentially re-evaluate the input string.
I was able to do this like so:
var escapedInput = document.querySelector("#text1").value;
var encodedChars = JSON.parse("\"" + escapedInput + "\"");
Now my encodedChars are 获取页面. Pass that to your translate.

Categories