I'm working on a small update to http://codepen.io/wesbos/pen/adQjoY and wanted to use a CSS variable to change the image, just to see if I can do it. So far, it's not working.
<img src=imageFile>
<style>
:root {
--image: 1;
--imageFile: '"https://source.unsplash.com/7bwQXzbF6KE/800x500"';
}
img {
src: var(--imageFile);
}
</style>
and I have some If, Then, Else, implemented in <script> ... </script>
to change the imageFile
variable.
In the DevTools console I get:
GET file:///Users/tim/bloc/JavaScript30-master/03%20-%20CSS%20Variables/imageFile net::ERR_FILE_NOT_FOUND
The image doesn't change. Can you help? Here is my full code before the update:
// get the inputs
const inputs = [].slice.call(document.querySelectorAll('.controls input'));
// listen for changes
inputs.forEach(input => input.addEventListener('change', handleUpdate));
inputs.forEach(input => input.addEventListener('mousemove', handleUpdate));
function handleUpdate(e) {
// append 'px' to the end of spacing and blur variables
const suffix = (this.id === 'base' ? '' : 'px');
document.documentElement.style.setProperty(`--${this.id}`, this.value + suffix);
}
:root {
--base: #ffc600;
--spacing: 10px;
--blur: 10px;
}
body {
text-align: center;
}
img {
padding: var(--spacing);
background: var(--base);
-webkit-filter: blur(var(--blur));
/* */
filter: blur(var(--blur));
}
.hl {
color: var(--base);
}
body {
background: #193549;
color: white;
font-family: 'helvetica neue', sans-serif;
font-weight: 100;
font-size: 50px;
}
.controls {
margin-bottom: 50px;
}
a {
color: var(--base);
text-decoration: none;
}
input {
width:100px;
}
<h2>Update CSS Variables with <span class='hl'>JS</span></h2>
<div class="controls">
<label>Spacing:</label>
<input type="range" id="spacing" min="10" max="200" value="10">
<label>Blur:</label>
<input type="range" id="blur" min="0" max="25" value="10">
<label>Base Color</label>
<input type="color" id="base" value="#ffc600">
</div>
<img src="http://unsplash.it/800/500?image=899">
<p class="love">Made by <a href="http://twitter.com/wesbos">@wesbos</a> </p>
<p class="love">Chrome 49+, Firefox 31+</p>
If you want to use CSS to specify the source of your file you can use something like this:
HTML:
CSS:
for your reference: https://jsfiddle.net/tqoLe7r3/