Javascript- How do I change the background-image property in css? - javascript

With Javascript, I am trying to change the background-image on my web app.
Here is how Im trying to do it:
const bgimg = {
backgroundImage: "URL('../../Images/arches.JPG')"
}
<div style={bgimg} id="bg_img">
This method works fine when I use a pic from the internet with it's url, but it wont let me add a local image. I can use the same pictures on my computer if I implement it right in css, like
.container_image {
background-image: url(./Images/yellow_stone_copy.JPG)
}
But I want to be able to change the background, while it's running, to an image on my computer. What am I doing wrong?

Make sure the url of the image you want to use is relative to the html file and not to the js file

Related

can't set backgroundImage in react?

Hey Guys I'm trying to build my portfolio site , I want to make the main page of the portfolio have a back ground image and when I navigate to other parts of the portfolio the background is just color , I handled setting the backgroundColor successfully but can't do the backgrounImage correctly .
Here is my code.
componentDidMount(){
this.props.changePage("Main Page");
document.body.style.backgroundImage="url('background.jpg')";
}
that's the code inside the main page component but there seems to be something wrong , is it a problem with the syntax itself or the approach itself is wrong ?
EDIT 1!!
that's the code I used for backgroundColor and it's working why isn't it working with the backgroundImage .
componentDidMount(){
this.props.changePage("About Me");
document.body.style.backgroundColor='black';
}
Set the className of element where you want to display your image equal to .bgImage.In CSS file(named as App.css) write down the code as given below that targets .bgImage and sets its background to the URL or Path provided and import the CSS file in your main file using import './App.css';
.bgImage {
background: url(./media/hero.jpg) no-repeat center center;
//some other properties
}
Your background image is in the wrong directory for create-react-app. Move ./src/background.jpg to ./public/background.jpg.

Changing a backgroundImage set via JavaScript using a CSS media query

I have a responsive menu on my website. In full size, hovering over a button changes the background of the whole menu (not the button!). As I believe that it is impossible to change the background of a div on hovering over one of its child elements via CSS (please correct me if I'm wrong), I do this via JavaScript. For each menu button, I have a function like the following. Each button gives a different background image.
function arme() {
if (document.documentElement.clientWidth > 590) {
var bild = "url('" + bildliste[3] + "')";
document.getElementById('auswahlbox').style.backgroundImage=bild;
}
}
As you can see, for lower resolutions (> 590px), the background of the menu does not change because the menu looks different then. The background then is always the same image. CSS looks like this:
#media only screen and (max-width: 590px) {
#auswahlbox { background:url(images/koerperbilder/koerperbg.jpg);
}
If I load my website in full size and then make the viewport smaller, the background of the menu changes to the image that is set via CSS. That's how it's supposed to work.
However, now to my problem: If I load my website in full size, hover over a random button (thus activating the JavaScript function above) and then make the viewport smaller, the background doesn't change. It stays the way it was set by hovering over the button. Apparently, a backgroundImage that was set via JavaScript beforehand can't be changed back by a simple CSS media query like the one above.
My question is: How can I change a backgroundImage that was set via JavaScript using a CSS media query? And if that is not possible, how can I solve my dilemma?
Right now, this problem is ruining the user experience. Since all other rules of the media query get applied (among them background-position and background-repeat), everything falls apart whenever someone resizes the viewport after hovering over a button. I wonder if someone can help.
Thank you in advance - and sorry for my bad English.
As you have set backgroundImage property through JavaScript
document.getElementById('auswahlbox').style.**backgroundImage**=bild;
You should set same property in CSS also. So use following code
#media only screen and (max-width: 590px) {
#auswahlbox { **background-image**:url(images/koerperbilder/koerperbg.jpg);
}

How to hide and retrieve a URL in CSS with Javascript

In CSS, I want to be able to specify a background image for a given selector without it actually being downloaded or rendered. I then want to be able to read the image URL with javascript, modify it in js, and then apply the modified URL to the selector for real so it will actually download and display. (I suppose that last part will have to be done with jQuery directly changing styles on each element, but that is not what this question is about.) This is part of some devious thing I'm trying to make really easy responsive images.
I have tried:
.sneaky {
background: url("youcantseemeyet.jpg");
background-image: url("blank.jpg");
}
But I can't find a way for javascript to know about the original background property.
Also tried:
.sneaky:after {
background: url("youcantseemeyet.jpg");
}
But I don't think javascript can see pseudo-elements.
Also tried:
.sneaky {
x-background: url("youcantseemeyet.jpg");
}
and:
.sneaky {
background: x-url("youcantseemeyet.jpg");
}
But I think javascript just tosses custom properties/values out the window.
How do CSS Polyfills work? Because they allow you to use CSS properties and values that would normally be invalid in a browser, so how does javascript access the CSS?
Another idea: I don't suppose there is a way to pre-empt the CSS with javascript, read the url() but block the file from downloading, is there?
I upvoted the question for your motivation to do this. Resposive Image resizing for Performance gain is a great way to reduce the bytes downloaded without affecting the quality of the page.
Here's one way of doing it: http://codepen.io/anon/pen/bNGgLZ
You can use html5 data attribute to store the url (so that the image is not downloaded initially) and then apply the image size based on the window size using javascript
<div class="sneaky" data-url="img_test.png">abcd</div>
<style>
.sneaky {
background: #000 url("transparent_placeholder.png");
color:#fff;
}
</style>
<script>
var el = document.querySelector(".sneaky");
alert(el.getAttribute("data-url"));
//Decide image size based on client window size and then assign backgroundImage property to download it from server
var size = "smaller";
el.backgroundImage = "url("+size+"_img_test.png)"
</script>
You can use the background position property to remove the image from rendering area and use window.getComputedStyle to retrieve the url
CSS
.sneaky {
background-image:url(youcantseemeyet.jpg);
background-position:-9999px -9999px;
}
Javascript
var url=window.getComputedStyle(document.querySelector('.sneaky'),null).backgroundImage
If you want to apply a second background images to .sneaky, better to include a sub div without padding/margin and apply second background to it
I figured out what to do. Kind of obvious now that I thought about it. Just hide the desired URL in a query string, like: url('/img/placeholder.gif?/path/to/real/image.jpg'). Ah, query strings, I love them.
UPDATE
A problem with using a query string is that every unique query string still results in a new HTTP request, even if it is ultimately returning the same resource. So, alternatively you can use a hash mark, like url('/img/placeholder.gif#/path/to/real/image.jpg'). When the image is requested, it will completely ignore the hash tag part, BUT you can still retrieve that information with javascript. It is just a bit tricky. Assuming you have no other URLs with hash tags in them (because why would you), you can simply retrieve a list of all selectors in all stylesheets which do use the hash tag part with the following script.
var selection = []
, sheets = document.styleSheets
, sheet, rule, i, j
for (i in sheets){
sheet = sheets[i]
for (j in sheet.cssRules) {
rule = sheet.cssRules[j]
if (/url\(.*#.*\)/.test(rule.cssText)) selection.push( rule.selectorText );
}
}

Dynamically edit .svg file that's set as background image

I added an svg image to the background of a div.
div#cover{
background-image:url('dwm.svg');
}
I would like to know if there is any way I could dynamically edit certain aspects of this svg such as fill, stroke , etc.
You can try having the svg as part of the DOM, do the modification and then set the background as a data uri of the modified svg pulled from the DOM.
While this might be kind of hacky it works
$('#bg').css('background-image', 'url(data:image/svg+xml;base64,'+btoa($('#svg').html())+')');
$('button').click(function(){
$('#fill').attr('fill', '#ff00ff');
$('#bg').css('background-image', 'url(data:image/svg+xml;base64,'+btoa($('#svg').html())+')');
});
<div id="bg"></div>
<div id="svg">[svg data]</div>
http://jsfiddle.net/zSRW5/
If you don't want to embed the svg you can always use ajax to get it.
No. I believe you can only do that if you embed the SVG within the page and reference it and even then, you would have to change the background value to something else and back to the reference, due to browser bugs.

Change PAGE background (not element BG) on any element hover.

I've been trying to change my PAGE background whenever I hover over an element. Currently I've uploaded different images into my web server, I would like to change my page background from one of the images, to another image when I hover over a div. How would I go about doing this? It doesn't matter if it's javascript, jquery, or css, the more answers the better so that I could learn a new way to do this :)
My css:
body{
background: url(../html/dest/back2.png);
height: 100% ;
background-attachment: fixed;
}
I have uploaded a new image called back2a.png. I would like to load this image in place of my previous image (back2.png) whenever the user hovers over an element. (Any element)
Note: I would also like to maintain the background-attachment:fixed on the new image.
The new image is simply a change of hue/saturation done in photoshop, nothing drastic it's the same size and everything.
Here is the page I'm trying to do this on.
http://hourtimeagent.com/html/c++.php
I appreciate answers! thank you!
jQuery:
$("div").hover(function() {
$("body").css("background", "url(../html/dest/back2a.png)");
});
If you want to change it back afterwards you can use the jQuery .blur method:
$("div").blur(function() {
$("body").css("background", "url(../html/dest/back2.png)");
});
The div selector can be changed to anything you want it to be on hovering. For example, if you have a div with the id of hover, use something like this:
$("div#hover").hover(function() {
$("body").css("background", "url(../html/dest/back2a.png)");
});
Or a class of hover:
$("div.hover").hover(function() {
$("body").css("background", "url(../html/dest/back2a.png)");
});
Javascript
To use straight javascript you'd have to add events to the elements on your page that you want to change the background with. I'd stick with jQuery as it does it for you, but if you'd prefer to use just javascript on a div you'd add:
<div onhover="myFunc();"></div>
And then the javascript would look like the following:
<script type="text/javascript>
function myFunc() {
document.body.style.background = "url(../html/dest/back2a.png)";
</script>

Categories