Style background image with JS not working - javascript

Ok, maybe its a stupid question with a little bug, but I'm trying fix this and I can not:
<style>
.pagar a {
width: 200px;
height: 85px;
display: block;
background-image: url('imagens/pagar.jpg');
background-repeat: no-repeat;
}
.pagar a:hover {
background-image: url('imagens/pagar-hover.jpg');
background-repeat: no-repeat; }
</style>
<script>
function clickado() {
document.getElementsByClassName('pagar')[0].style.backgroundImage = 'url("imagens/pagar-clickado.jpg")';
}
</script>
HTML:
<div class="pagar" id="pagar" ></div>
The problem:
The .style.backgroundImage just does not change to "imagens/pagar-clickado.jpg", the the path is correct, I do not get error in console and ('pagar')[0] is also correct too.

I think you wanted to target the a element inside the div.pagar.
You can do something like this:
HTML
<div class="pagar" ></div>
Javascript
function clickado() {
document.getElementById('pagar').style.backgroundImage = 'url("imagens/pagar-clickado.jpg")';
}

You can try add new style class for the event click:
.pagar.click a:hover {
background-image: url('imagens/pagar-clickado.jpg');
background-repeat: no-repeat;
}
And change the function javascript:
function clickado() {
document.getElementById('pagar').classList.add('click');
}
With the new api for working with classes, it is more easier

You could write a much better solution attaching a class with your javascript to the '.pagar' element, for example "clicked". Then you could add a couple of lines to your CSS:
.pagar.clicked a,
.pagar.clicked a:hover {
background-image: url('imagens/pagar-clickado.jpg');
}
This is the javascript of course:
<script>
function clickado() {
document.getElementsByClassName('pagar')[0].className += 'clicked';
}
</script>
I learned that, to keep code simple and mantainable, moving style definition to CSS (removing it from javascript) is usually the best practice to follow.

Related

Selecting a background style using javascript - how to fix a simple syntax error?

I want to just change the background when clicking the button. However, I cannot get the variable change to fetch the background of div test2 and store it as a variable. I know this because alerting the value of test2 shows undefined.
I know this seems like a simple fix but I cannot actually find a solution. Is this just a simple syntax error or am I missing something?
An explanation of why this happens would be much appreciated, thanks.
var el = document.getElementById('test');
function changeBG() {
var change = document.getElementById('test2').background;
el.style.background = change;
}
#test {
background: url('http://i.dailymail.co.uk/i/pix/2017/08/15/19/434758D400000578-4793442-image-a-5_1502822599189.jpg');
width: 200px;
height: 200px;
background-size: cover;
background-position: center;
}
#test2 {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Lioness_and_cub.jpg/240px-Lioness_and_cub.jpg');
}
<div id="test"></div>
<button onclick="changeBG();">hi</button>
There are a couple reasons for the error/undefined variable. First, there isn't an element with the id 'test2' in your html. You have only assigned css style to the id 'test2'. There is only a div with the id 'test'. The other problem is HTML elements do not have the property 'background'. To change the background you would need to use the 'style' property as in document.getElementById('test2').style.background = "url(...)";
There are several ways to resolve this, below is one approach using classes.
Remove the background attribute from the div id and create two
classes, background and background2.
In the html, add the background to the test div as the default
class (background image).
Use the toggle() method to alternate assignment of the class to the
div.
Since the original class background was already assigned it will be removed and background2 is added. If you are only trying to change the background once, then you can just simply reassign the class (see commented lines).
toggle
style property
Note: The reason you can't keep the background attribute as part of the original div's id css and add the class with the new background is because the id takes precedent and will override any class attributes with the same name unless !important is added to the end of the class attribute value (background: url(..) !important;) though that method should be avoided if possible. Also, The classList property is not supported in Internet Explorer 9 if that matters.
var el = document.getElementById('test');
function changeBG() {
//to change the background once
//el.className = "background2";
el.classList.toggle('background');
el.classList.toggle('background2');
}
#test {
width: 200px;
height: 200px;
background-size: cover;
background-position: center;
}
.background{
background: url('http://i.dailymail.co.uk/i/pix/2017/08/15/19/434758D400000578-4793442-image-a-5_1502822599189.jpg');
}
.background2 {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Lioness_and_cub.jpg/240px-Lioness_and_cub.jpg');
}
<div id="test" class ="background"></div>
<button onclick="changeBG();">hi</button>
If all you're looking to do is change style properties, you can simply toggle classes. Its totally unnecessary to create variables to do this unless you're just trying to learn something.
var el = document.getElementById('test');
function changeBG() {
el.classList.toggle('test1');
el.classList.toggle('test2');
}
#test {
width: 200px;
height: 200px;
background-size: cover;
background-position: center;
}
.test1 {
background: url('http://i.dailymail.co.uk/i/pix/2017/08/15/19/434758D400000578-4793442-image-a-5_1502822599189.jpg');
}
.test2 {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Lioness_and_cub.jpg/240px-Lioness_and_cub.jpg');
}
<div id="test" class="test1"></div>
<button onclick="changeBG();">change background</button>
If you are looking for an old-school solution.
function changeBG() {
var el = document.getElementById('test');
var value = null;
for (let i = 0; i < document.styleSheets.length; i++) {
const mysheet = document.styleSheets[i];
const myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
if(myrules){
for (let j = 0; j < myrules.length; j++) {
if (myrules[j].selectorText &&
myrules[j].selectorText.toLowerCase() === '#test2') {
value = myrules[j].style['background'];
}
}
}
}
if(value){
el.style.background = value;
}else{
alert("test2 not found");
}
}
#test {
background: url('http://i.dailymail.co.uk/i/pix/2017/08/15/19/434758D400000578-4793442-image-a-5_1502822599189.jpg');
width: 200px;
height: 200px;
background-size: cover;
background-position: center;
}
#test2 {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Lioness_and_cub.jpg/240px-Lioness_and_cub.jpg');
width: 200px;
height: 200px;
background-size: cover;
background-position: center;
}
<h4> if you are looking for an old-school solution</h4>
<div id="test"></div>
<button onclick="javascript:changeBG();">hi</button>
<div id="test2"></div>

When is a background image loaded when using addClass()?

I did some research on here, and I left with the impression that a background image is not loaded if the associated div class is not in the HTML. This led me to believe that when using addClass() to assign a div the class with the background image, I would need to refresh the CSS to make the image load. However, it is showing up without refreshing the CSS.
Does including the class in the JavaScript cause the CSS to pre-load the image, so it is ready when the class is added? If not, why is the background image available without refreshing the CSS?
HTML
<body>
<div class="no-class"></div>
</body>
CSS
.background-image {
background-image: url('image.png');
background-size: 100% 100%;
}
.no-class {
height: 500px;
width:500px;
background-color: red;
}
JS
$(document).ready(function () {
$('.no-class').click(function() {
$('.no-class').toggleClass('background-image');
});
})
rearrange classes
.no-class {
height: 500px;
width:500px;
background-color: red;
}
.background-image {
background-image: url('image.png');
background-size: 100% 100%;
}
And be sure to include Jquery
DEMO
and if you have more than 1 element with class .no-class .. use $(this)
$(document).ready(function () {
$('.no-class').click(function() {
$(this).toggleClass('background-image');
});
})

Javascript error: element is null

Here is all of my code... The inline JavaScript alert is firing off nicely, but the external alert is not. Whenever I reload the page I get a console error log saying "TypeError: tileBlock is null".. Any ideas? I've yet to come across this issue and I'd rather not be forced into writing all of my Javascript event handlers inline. Thanks!
#tileBlock {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: #0b0b0b;
background-position: center;
background-repeat: no-repeat;
background-image: url(photo.jpg);
border: 20px solid #fff;
background-size: cover;
}
#media (max-width: 400px) {
#tileBlock {
border-width: 8px;
}
}
<body>
<div class="wrapper" id="tileBlock" onclick="alert('You clicked (inline)')"></div>
</body>
var tileBlock = document.getElementById('tileBlock');
tileBlock.onclick = function() {
alert('you clicked(external script)');
}
Include jquery library and try this:
$('#tileBlock').onclick(function(){
alert('you clicked(external script)');
});
Also I have tried your code and it works.(not my jquery)
Try this: http://jsfiddle.net/XcsN/evK3v/
I just needed a window.onload... Thanks everyone for the help!
window.onload=function(){
var tileBlock = document.getElementById('tileBlock');
tileBlock.onclick = function() {
alert('you clicked yes');
}
};
No need window before since it's reserved
onload=()=>{
let elem // etc..
elem.onclick=()=> // stuff ..
}
fiddle

How to make onclick event to div background image?

I created a div in html and assigned a background image to it, and i want to make an onclick event to that photo and don't know how, that's the div :
.add_btn {
background-color: #099;
position: absolute;
height: 35px;
width: 200px;
background-image: url(img/add.png);
background-repeat: no-repeat;
background-position: center center;
top: 265px;
You didn't give any information about your DOM except that you have an element with that class. It's hard to give a good answer but I'll try.
The following code will attach a function to the onclick events of all the elements with the add_btn class.
document.getElementsByClassName("add_btn").onclick =
function () {
alert("Hello");
};
Background image click is not possible. Because you have a foreground layer.
But you can use this JQuery for foreground image click...
$('.className > .Inner_Classname2= > img').click(function(e) {
alert("Ok");
});

Change Background when part of it is hovered

i am totally new in web design, and i am right now struggling with creating part of my website, i need to somehow make this happen:
When PART of the BODY BACKGROUND is HOVERED, make the background change to "B", and when the mouse is not over that part, I need it to change back to background "A".
I have seen some examples here but as i am a beginner, i have no idea how to use javascript, if you could please give me some light here, either on pure CSS or on how to apply javascript.
This is accomplished very easily using a third party javascript library called JQuery http://jquery.com, you can see a working example here: http://jsfiddle.net/bbp8G/
$(document).ready(function(){
$("#hover").mouseenter(function(){
$(this).css("background","#009900");
}).mouseleave(function(){
$(this).css("background","#ffffff");
});
});
Here's the easiest way I know how to do what you've described...
<!-- POSITION THIS DIV WHEREVER YOU WANT THE
USER TO HOVER SO THAT THE BACKGROUND WILL CHANGE -->
<div id="hover">
</div>
<!-- PUT THIS CODE IN YOUR <HEAD> -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" />
<style>
#hover { width: 200px; height: 200px; position: relative; top: 200px; background: green; }
.myNewBackround { background-color: red; }
</style>
<script>
$(document).ready(function() {
// when the #hover DIV is hovered, change the background of the body
$('#hover').hover(function() {
$('body').addClass('myNewBackground');
});
});
</script>
Here's a JS FIDDLE:
http://jsfiddle.net/ZKaJn/
Or you can do it with pure CSS
<div id="left"> </div>
<div id="right"> </div>
And the CSS part:
#left
{
background-color:#000;
float:left;
width:50%;
height:200px;
}
#right
{
background-color:#FF0;
float:right;
width:50%;
height:200px;
}
#right:hover
{
background-color:#00F;
}
#left:hover
{
background-color:#F00;
}
You can replace the div's and values with whatever you like, the main part is the #right:hover and #left:hover
Actually with just css it is not possible to change the background of the body when hovering a DOM element. This is because CSS does not allow you (yet) to travel up the DOM tree (select a parent), only down (select a child).
That being said, it is however possible to mimic the effect, and it is even quiet easy if it is the body background you want to change. You can lay a pseudo element with a background on top of your body background, and underneath the actual content. This way it looks as if the body background has changed.
The css to achieve this would look something like this:
.hover-me:hover:after {
content: '';
top: 0;
left: 0;
right: 0;
bottom: 0;
position: fixed;
background: url(http://placekitten.com/600/300) center center;
background-size: cover;
z-index: -1;
}
And a small fiddle to demonstrate: http://jsfiddle.net/3dwzt/
Should be compatible with IE8 and up

Categories