unable to change image in a div through javascript - javascript

Here is my code:
<!DOCTYPE html>
<html>
<body>
<script>
function light() {
if (document.getElementById("push").value == "OFF") {
document.getElementById("bulb").style.backgroundImage = url("1.png");
document.getElementByID("push").value = "ON";
}
else {
document.getElementById("bulb").style.backgroundImage = url("2.png");
document.getElementByID("push").value = "OFF";
}
}
</script>
<center>
<input type="button" id="push" onclick="light()" value="OFF" />
<div id="bulb" style="background-image:url(2.png);width:320px;height:420px">
</div>enter code here
</center>
</body>
</html>

This line:
document.getElementById("bulb").style.backgroundImage = url("1.png");
attempts to call a function called url and pass a string to it, and then assign the result of that to the backgroundImage property.
Instead, you want to assign a string to backgroundImage directly:
document.getElementById("bulb").style.backgroundImage = "url(1.png)";
// Note ------------------------------------------------^----^----^^
Example:
document.getElementById("bulb").style.backgroundImage = "url(https://lh3.googleusercontent.com/-qJYMzFfIels/AAAAAAAAAAI/AAAAAAAAAGM/16Ir8NxI3gE/photo.jpg?sz=32)";
<div id="bulb" style="width: 32px; height: 32px"></div>
That said, it would be better to define your styling and such in CSS and then associate those styles with elements using selectors, for instance via a class association:
CSS:
.class-saying-what-the-image-represents {
background-image: url(1.png);
}
JavaScript:
document.getElementById("bulb").classList.add("class-saying-what-the-image-represents");
Example:
document.getElementById("bulb").classList.add("class-saying-what-the-image-represents");
.class-saying-what-the-image-represents {
background-image: url(https://lh3.googleusercontent.com/-qJYMzFfIels/AAAAAAAAAAI/AAAAAAAAAGM/16Ir8NxI3gE/photo.jpg?sz=32);
}
<div id="bulb" style="width: 32px; height: 32px"></div>

Related

Span value inside a style value

this maybe a very stupid question, but is this possibe ?
well i have a sort of a slider on a html page.
this is what it shows up like now:
<p>Illustrator</p>
<div class="w3-light-grey w3-round-xlarge w3-small">
<div class="w3-container w3-center w3-round-xlarge w3-teal" style="width:75%">75%</div>
</div>
This shows up a bar,
well what want to achieve is if its possible to change that value 75% to my script data :
style="width:75%">
like i have a script, it retrieves values from my server:
var input = "10;11;15";
var arr = input.split(";");
document.getElementById("humid").innerHTML = (arr[0 ]);
this shows up my data just normal
<span id="humid">0</span>
what i want to do is something like this, but i don't know how:
I want this value from style="width:75%"> to be the humid value.
so if my humid value is 50% the width goes 50%
i did try this but no result
style="width:humid+%">
or style="width:(humid)+%">
i'm still learning,
regards
<!DOCTYPE html>
<html>
<title>TESt</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
html,body,h1,h2,h3,h4,h5,h6 {font-family: "Roboto", sans-serif}
</style>
<body class="w3-light-grey">
<p>Original</p>
<div class="w3-light-grey w3-round-xlarge w3-small">
<div class="w3-container w3-center w3-round-xlarge w3-teal" style="width:75%">75%</div>
</div>
<p>Media</p>
<div class="w3-light-grey w3-round-xlarge w3-small">
<div class="w3-container w3-center w3-round-xlarge w3-teal" style="#humid">0</div>
</body>
<script>
var input = "10;11;15";
var arr = input.split(";");
//alert(arr[1 ]);
document.getElementById("humid").innerHTML = (arr[0]);
document.getElementById("temp").innerHTML = (arr[1 ]);
document.getElementById("uv").innerHTML = (arr[2 ]);
</script>
</html>
Retrieve my input:
function readForestall() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ForestAll").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "readFORESTALL", false);
xhttp.send();
}
setInterval(function() {
readForestall();
}, 5000);
If I understand your question right, you want to change the width of an element based on a variable you receive. In that case you can change the inline style with JavaScript. You just need to grab the element and set the style by assigning values to the properties of the element's style property.
If you want to change the width, you can use the following:
element.style.width = '50%'
It sets the width to 50%. You can also include a variable like this:
const width = 50
element.style.width = `${width}%`
I've created a snippet below where you can set the value by using an input and it updates both the width and the content of that div. You can click on the "Run code snippet button" and see the result in live.
const barLeft = document.querySelector('#bar-left');
const barRight = document.querySelector('#bar-right');
const input = document.querySelector('[name="width"]');
const error = document.querySelector('.error');
input.addEventListener('input', (e) => {
const widthLeft = Number(e.target.value);
const widthRight = 100 - widthLeft;
if (widthLeft < 0 || widthLeft > 100) {
error.textContent =
"We don't do that here. Width must be between 0 and 100.";
return;
}
error.textContent = '';
barLeft.textContent = `${widthLeft}%`;
barLeft.style.width = `${widthLeft}%`;
barRight.textContent = `${widthRight}%`;
barRight.style.width = `${widthRight}%`;
});
body {
font-family: sans-serif;
margin: 0;
text-align: center;
}
.outer {
display: flex;
margin-bottom: 2rem;
}
.inner {
background-color: lightcoral;
box-shadow: 0 -4px 0 rgba(0, 0, 0, 0.2) inset;
height: 100%;
padding: 1rem;
}
.inner--blue {
background-color: lightblue;
}
.controls {
margin-bottom: 1rem;
}
input {
font-family: inherit;
font-size: inherit;
padding: 0.5rem 1rem;
}
.error {
color: #d32f2f;
}
<div class="outer">
<div class="inner" id="bar-left" style="width: 75%">75%</div>
<div class="inner inner--blue" id="bar-right" style="width: 25%">25%</div>
</div>
<div class="controls">
<label for="width">First bar's width:</label>
<input type="number" name="width" id="width" min="5" max="95" value="75" />
</div>
<div class="error"></div>
Update: Updated your example below. Make sure you close your tags, and check out how to add ids to elements.
<body class="w3-light-grey">
<p>Media</p>
<div class="w3-light-grey w3-round-xlarge w3-small">
<div class="w3-container w3-center w3-round-xlarge w3-teal" id="humid">
0
</div>
</div>
div>
<script>
var input = '10;11;15';
var arr = input.split(';');
// update the content of the div with ID "humid"
document.getElementById('humid').textContent = arr[0];
// change the width of the div with ID "humid"
document.getElementById('humid').style.width = `${arr[0]}%`;
</script>
</body>
Tranq,
i am not exactly sure why you would want to call the width from an array and use DOM when you can simply use CSS to accomplish this with #media instead. correct me if i am wrong, but you're just trying to adjust the width based on values of the current width of the device? this seems like a whole lot of work for what is a simple solution.
use something like to set the appropriate widths depending on the screen widths:
#media only screen and (max-width: 600px) {
#humid { width: 75%; }
}
also, it is likely you're not passing your array properly and it is returning NULL(0). you can check this via a debugger and ensure it is being passed properly. FireFox has a Great built in debugger for this. use CMD/CTRL+SHIFT+K to open the debugger in FireFox.
P.S. you are not passing the array properly. you're setting it to change the 'innerHTML' which changes everything inside of the
document.getElementById("humid").innerHTML = (arr[0 ]);
if you change "(arr[0 ]);" to something like "string" it will replace the value 0 to "string".

Need to enlarge image at click and then reduce it again by clicking again on external javascript file

This large image is defined in the index.html with a class="small" attribute so it shows as a thumbnail.
<img id="smart_thumbnail" class="small" src="https://image.jpg">
On a separate .js file need to create a function to bring it back to it's normal size and then back to thumbnail by clicking it again. NEED to use if/else. What I am trying to do is to switch between class="" and class="small"
So far I have this but it is not working:
document.addEventListener("DOMContentLoaded", function(event) {
var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.addEventListener("click", function() {
if(thumbnailElement.className = "small";){thumbnailElement.className = "";}
else
{thumbnailElement.className = "small";}
});
});
Any suggestions? Thanks.
Here is something that I made work. It uses JS style properties to change it, not CSS classes. You could copy or reference it:
var imgEl = document.getElementById("Img");
var isBig = false;
imgEl.addEventListener("click", function() {
if (isBig) {
imgEl.style.width = "30px";
imgEl.style.height = "30px";
isBig = false;
} else {
imgEl.style.width = "100px";
imgEl.style.height = "100px";
isBig = true;
}
})
#Img {
border: 1px solid black;
background-color: red;
width: 30px;
height: 30px;
transition: 1s;
}
<div id="Img">
The CSS class switcher isn't working because '=' is not an equal operator, it is an assignment operator. use '==' or '===' for equal operators.
The code above will only run once when the website is initially loaded. To solve this problem, you will need to modify the code so that it is constantly listening for an event.
The code for it should look something similar to the following:
<!DOCTYPE html>
<html>
<head>
<title>Resizing a square with event listeners</title>
<style type="text/css">
.small {
width: 50px;
height: 50px;
}
.large {
width: 100px;
height: 100px;
}
#smart_thumbnail {
background-color: blue;
}
</style>
</head>
<body>
<div id="smart_thumbnail" class="large"></div>
<script>
var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.addEventListener("click", function() {
if (this.className == "small") {this.className = "large";}
else {this.className = "small";}
});
</script>
</body>
</html>
I also modified the smart_thumbnail so that it has a large/normal size class as well as a small class.

Change CSS of div when clicking on a button

Is it possible to change the background image of a div when a button outside of the div is selected?
e.g.
HTML
<div id="change"></div>
<div id="buttons">
<button class="button1">this</button>
<button class="button2">that</button>
<button class="button3">there</button>
<button class="button4">then</button>
</div>
CSS
#change{
background-image: url("this.jpg")
}
Desired effect when clicking button 2 (same for each button; 3 = there.jpg, 4 = then.jpg)
#change{
background-image: url("that.jpg")
}
Using javascript you can set the backgroundImage. Using jQuery you'd use $.css('background-image');
You could also use JS/jQuery to add a class to the element, and you can set the background-image in CSS for that class.
document.getElementById('button').addEventListener('click',function() {
document.getElementById('change').style.backgroundImage = 'url(https://futurism.com/wp-content/uploads/2015/11/neildegrassetyson.jpg)';
})
#change {
background: #eee;
width: 600px;
height: 375px;
}
<button id="button">button</button>
<div id="change"></div>
document.getElementById('button').addEventListener('click',function() {
document.getElementById('change').classList.add('bg');
})
#change {
background: #eee;
width: 600px;
height: 375px;
}
#change.bg {
background-image: url(https://futurism.com/wp-content/uploads/2015/11/neildegrassetyson.jpg)
}
<button id="button">button</button>
<div id="change"></div>
You can do this but it will require JavaScript:
Your HTML:
<div id="buttons">
<button class="button1" onclick="changeBG('image1.jpg')">this</button>
<button class="button2" onclick="changeBG('image2.jpg')">that</button>
<button class="button3" onclick="changeBG('image3.jpg')">there</button>
<button class="button4" onclick="changeBG('image4.jpg')">then</button>
</div>
<script>
function changeBG(image) {
var urlString = "url(" + image + ")";
document.getElementById('change').style.backgroundImage = urlString;
}
</script>
This is not the prettiest way to do this but it should accomplish getting you started.
This is what you need in jQuery :D
$('#buttons button').on('click',function() {
var val = $(this).text();
$('#change').css('background-image','url('+val+'.jpg)');
});
put the script inside $(document).ready(function() {

Change div background color on click event

I am trying to change div color on click but it is not working:
<html>
<head>
<script>
function data(){
var MyDiv1 = document.getElementById('newdata').innerHTML;
alert(MyDiv1)
if(MyDiv1==1) {
document.getElementsById('newdata').style.backgroundColor = "green";
}
}
</script>
</head>
<body >
<div id="newdata" style="background-color: red; width: 100px;height: 50px;">
1
</div>
Logout
</body>
</html>
Where am I wrong here?
Any help will be appreciated
<html>
<head>
</head>
<body >
<div id="newdata" style="background-color: red; width: 100px;height: 50px;">
1
</div>
Logout
</body>
</html>
<script>
function data(){
document.getElementById('newdata').style.backgroundColor = "green";
}
</script>
http://jsfiddle.net/n2uk4br1/
1) Script at the end;
2) Element not Elements
3) Call the right div name
4) That alert and if don't have a purpose
There were a couple of problems with your attempt. The following snippet does what you want:
function data(){
var myDiv = document.getElementById('newdata');
var content = myDiv.innerHTML;
if (content.trim() === "1") {
myDiv.style.backgroundColor = "green";
}
}
<div id="newdata" style="background-color: red; width: 100px;height: 50px;">
1
</div>
Logout
Firstly, you must be careful to distinguish between your <div> element and its contents. I have put the two into separate variables. I have used .trim() to remove any leading and trailing spaces from the contents of the <div> and also used the strict comparison ===.
it should be newdata
document.getElementById('newdata').style.backgroundColor = "green";
so your function will be
function data(){
var MyDiv1 = document.getElementById('newdata').innerHTML;
alert(MyDiv1)
if(MyDiv1==1) {
document.getElementById('newdata').style.backgroundColor = "green";
}
}

jQuery/Javascript : How to prepend elements without going back to the top of last prepended element?

Whenever I click prepend, after all elements are prepended, the view of the chat area switches to the top of the chat area or the last prepended element. This is different from append, whereby after all elements are appended, the view of the chat area does not switch to the end of the chat area or last appended element but still stays at its previous position.
How do I make the prepend function act in the same way as append in the sense that the view of the chat area does not change similar to FB's load previous message function?
Here is a sample code that illustrates what I mean.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<style type="text/css">
.chatbox{
border:1px solid #2a6496;
height: 600px;
margin-top:50px;
}
.chatbox div{
height: 100%;
}
.rightP{
border-left: 1px solid #2a6496;
}
.rightP .contents{
border-bottom: 1px solid #2a6496;
height: 70%;
}
.rightP .send{
padding : 5% 5% 5% 5%;
height: 30%;
}
#response{
height: 200px;
overflow-y: scroll;
overflow-wrap: break-word;
}
</style>
<script>
function appendMessage()
{
var data = 'hello';
var message = document.createElement('p');
message.innerHTML = data;
console.log(message.innerHTML);
$('#response').append(message);
$('#response').append($('.load'));
}
function prependMessage()
{
for(var $i = 0;$i<10;$i++)
{
var data = 'hello'+$i;
var message = document.createElement('p');
message.innerHTML = data;
console.log(message.innerHTML);
$('#response').prepend(message);
$('#response').prepend($('.load2'));
}
}
</script>
<body>
<div class="container">
<div class="chatbox">
<div class="col-sm-8 rightP">
<div class="row contents">
<div class="row msg">
<div id="response" class="msg form-group">
<a onclick="return appendMessage()" class="load btn btn-default">Append</a>
<a onclick="return prependMessage()" class="load2 btn btn-default">Prepend</a>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
In HTML there should be return in your onlick:
<a onclick="return loadMessage();" class="load btn btn-default">Load More Msg</a>
In JS you need to add return false to your function loadMessage.
var loadMessage = function(){
var firstMessage = $messagesWrapper.find('> p:nth-child(2)');
$.ajax({
....
if(messages.length<10){
$('.load').hide();//hide the load button if remaining messages to load is <10
}
success: function(messages){
$.each(messages, function() {
prependMessage(this);
});
},
....
});
return false;
};
Try this:
<div id="response" class="msg form-group">
<a onclick="loadMessage(); return false;" class="load btn btn-default">Load More Msg</a>
</div>
If this doesn't work, try another way:
var loadMessage = function(){
e.preventDefault(); // preventing any scroll action
var firstMessage = $messagesWrapper.find('> p:nth-child(2)');
(...)
And
var prependMessage = function(data){
e.preventDefault(); // preventing any scroll action
var message = document.createElement('p');
(...)
If this doesn't work please provide the whole code so we can reproduce.

Categories

Resources