Javascript element.style.backgroundImage not loading image - javascript

Not sure what I'm missing here...
window.onload = function() {
var testDiv = document.createElement("div");
testDiv.style.backgroundImage = "url('http://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/2000px-Smiley.svg.png')";
document.body.appendChild(testDiv);
}

The issue is you're setting a background-image on a div with no height or width. Add those:
window.onload = function() {
var testDiv = document.createElement("div");
testDiv.style.backgroundImage = "url('http://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/2000px-Smiley.svg.png')";
testDiv.style.backgroundSize="cover"; //image is large, you dont need this if you dont want
testDiv.style.height="100px"; //add some value
testDiv.style.width="100px"; //add some value
document.body.appendChild(testDiv);
}
FIDDLE

Related

JS DOM createElements and appendChild not working

I am trying to create a website with information of some students. Hence I need to create dynamic profile cards and append them to body. But DOM always gets me.
function student(src, name) {
this.src = src;
this.name = name;
}
var student1 = student(1, "ABC");
var card = document.createElement('div');
card.className = 'card';
var image = document.createElement('img');
image.src = 'images\/students\/' + student1.src + '.jpg';
card.appendChild(image);
var stuName = document.createElement('p');
stuName.className = 'name';
var stuNameText = document.createTextNode(student1.name);
stuName.appendChild(stuNameText);
card.appendChild(stuName);
However nothing is showing up on the screen. placeHere is the id of body. Any help will be appreciated.
Edit:
Apparently applying all necessary changes and moving my script tag to body helps.
the way you creating Student1 Object is wrong
var student1 = new student(1, "ABC");
you forget new keywork
function student(src, name) {
this.src = src;
this.name = name;
}
var student1 = new student(1, "ABC");
var card = document.createElement('div');
card.className = 'card';
var image = document.createElement('img');
image.src = 'images\/students\/' + student1.src + '.jpg';
card.appendChild(image);
var stuName = document.createElement('p');
stuName.className = 'name';
var stuNameText = document.createTextNode(student1.name);
stuName.appendChild(stuNameText);
card.appendChild(stuName);
var main=document.getElementById('main')
main.appendChild(card)
.card{ color: palevioletred;
background: yellow;}
<div id="main"></div>
You have to append all these newly created elements to a div already in the DOM or body tag will work too. Currently, the elements you created are not attached to DOM. So lets say you have a div
<div id="mydiv"></div>
you can append to that div you newly created elements like this:
ley mydiv = document.getElementById('mydiv');
mydiv.appendChild(card);
or you can append it to the body itself like so:
ley body= document.getElementByTagName('body');
body.appendChild(card);
You didn't append your code to any DOM element, create new div in body and append your code into that div.
<div id="stdCard"></div>
and then you can use innerHTML to append card into parent div created. document.getElementById("stdCard").innerHTML = card;

Image swap when hovering

I've created a snippet to swap images between no underscore and '_1' in the source path when hovering and leaving the .hover()
Sometimes I see an issue whereby the next image I hover over get's the 'styled' image from the previous image i hovered over (this is inconsistent!) with '_1'?
I think it has to do with the speed at which you hover over the images.
I'm using $(this) to refer to the div the user is currently hovering over and maybe it's inconsistently storing the src for the img and referencing it too soon?
Please see below a video demonstrating my issue:
http://screencast.com/t/lJEDb5lyTXj5
PS: I don't have access to the source code - I am injecting this code onto the site, (So i can't manipulate the divs/images without JS)
<head>
<style>
.js div.result.product {
display: none;
}
</style>
<script>
$('html').addClass('js');
</script>
<script>
$( document ).ready(function() {
$('div.result.product').show();
});
</script>
</head>
<script>
console.log($('div.result-image').length);
// Function to set all images with _1 to no "_1".
$( "div.result-image > a > img" ).each(function() {
console.log('one image');
var styled = "_1";
var revertStyledOriginal = $(this).attr('src');
var preset = "?hei=245&qlt=85,1&wid=245&fmt=jpeg&resMode=bicub&op_sharpen=1";
// if the img is silo
var s = revertStyledOriginal;
// Only takes everything up until the "_"
unstyle = s.substring(0, s.indexOf('_'));
// add the preset back onto the src to make the img crisp
var unstyled = unstyle + preset;
// sets this instance of the image in the each loop to the "new link" with removed "_1"
$(this).attr('src', unstyled);
});
// Hover Function
$('div.result.product').hover(function myfunc() {
//Store 'this' as a reference to the current product image to be referred to when switching images
var selection = $(this);
$link = selection.find('img').attr('src');
$parsed = $link;
var styled = "_1";
var revertStyledOriginal = selection.find('img').attr('src');
var preset = "?hei=245&qlt=85,1&wid=245&fmt=jpeg&resMode=bicub&op_sharpen=1";
//if the img is silo
if(revertStyledOriginal.indexOf(styled) === -1 && ($link !== "http://www.kirklands.com/assets/HTML/MVS/AB_tests/NextPageButton/Next_Page_Buttons_Page_2.jpg"))
{
$preset = "?hei=245&qlt=85,1&wid=245&fmt=jpeg&resMode=bicub&op_sharpen=1";
//Need to remove preset to add _1 (then readd preset).
$removedPreset = $parsed.substring(0, $parsed.indexOf('?'));
var Unstyled = $removedPreset + $preset;
var Styled = $removedPreset + "_1" + $preset;
function checkImage(src) {
var img = new Image();
img.onload = function() {
// code to set the src on success
selection.find('img').attr('src', Styled)
//console.log('exists');
//console.log(revertStyledOriginal);
};
img.onerror = function() {
selection.find('img').attr('src', Unstyled)
console.log('doesnt exist');
//console.log();
};
img.src = src; // fires off loading of image
}
checkImage(Styled);
}
//if the img is styled
else {}
//$( this ).attr("src",);
},
//Function to reset the image on when you exit hover of img
function() {
$original = $(this).find('img').attr('src')
$removedPreset = $parsed.substring(0, $parsed.indexOf('?'));
$link = $removedPreset + $preset;
if ($original !== "http://www.kirklands.com/assets/HTML/MVS/AB_tests/NextPageButton/Next_Page_Buttons_Page_2.jpg") {
// set on hover image src to silo
$(this).find('img').attr('src', $link)
}
});
</script>

Create div above other div only with javascript

I need create a div above another div, but I dont have access to the css file, thus everything needs to be done via JavaScript.
This is my wrong code:
var div = document.getElementById("down");
var divAbove = document.createElement("div");
divAbove.id = "up";
divAbove.style.background = "red";
divAbove.style.position = "absolute";
divAbove.style.width = "150px"
div.appendChild(divAbove );
I can't see the new div.
If you can pinpoint the container element you can make use of .insertBefore()
More Info (docs)
var container = document.getElementById("container");
var div = document.getElementById("down");
var divAbove = document.createElement("div");
divAbove.id = "up";
divAbove.style.backgroundColor = "red";
divAbove.style.width = "110px"
divAbove.style.height = "60px"
divAbove.innerHTML = "Added via JS"
container.insertBefore(divAbove, div);
<div id='container'>
<div id='down' style='height: 60px; width: 110px; background-color: yellow'>
Existing element
</div>
</div>
This work.
var div = document.getElementById("down");
var divAbove=document.createElement("div");
divAbove.id = "up";
divAbove.style.background = "red";
divAbove.style.position = "absolute";
divAbove.style.width = "150px";
divAbove.style.height= "150px";
div.appendChild(divAbove);
From this point I would say that the div is there, but due to a typo in divAbov.style.background = "red"; it does not have a visible background. Try fixing the typo.
If the problem persists, please post your console log if there is any errors in there.
The reason you can't see new div is that you didn't give any body to it. For example, it may be a case to write before appending divAbove the following:
divAbove.innerHTML = "Hello World";

Check if an element has a background-image with pure JS?

What is the correct way to check if a particular element has a background-image associated with it, in pure Javascript?
Right now I have this:
var elementComputedStyle = window.getComputedStyle(element);
var hasBGImage = elementComputedStyle.getPropertyValue('background-image') !== 'none'
What you have works, but there are alternate ways of finding the property that you might find easier. I don't believe there is a single 'correct' way to do it, however.
Just javascript:
var hasBGImage = element.style.backgroundImage !== '';
Using jQuery:
var hasBGImage = $(element).css('background-image') !== 'none';
Make sure you declare the background image "inline", otherwise .style.backgroundImage won't work.
<script>
window.onload=function() {
var bg = document.getElementById('el').style.backgroundImage.length!=0;
alert(bg);
}
</script>
<div id='el' style="background-image: url('a.jpg');"></div>
If you can use inline CSS, that's the way. If, for some reason, you can't use that, let me know, I'll try to find out something else :)
I used this code in last one project and works perfect
// Check all background images exists
var imageURLs = $('.image-container ');
imageURLs.each(function(index, element){
var imageURL = $(element).css('background-image').replace('url("', '').replace('")', '');
var img = new Image();
img.onerror = function() { $(element).css('background-image','url(/build/images/missing-image.svg)'); };
img.src = imageURL;
});

Cannot remove a div in Javascript

I'm trying to remove a div in Javascript but 'its not working. I get no error in my console yet the function does get called.
I don't understand what I have done wrong, so I'm hoping someone can explain. This is how it works:
function menu_load(type){
document.getElementById(type).onclick = function(){ menu_unload(type); }
var width = 100;
var height = 100;
var d = document.createElement('div');
d.id = 'menu';
d.className = 'menu';
d.style.width = width + 'px';
d.style.height = height + 'px';
document.getElementById('G').appendChild(d);
}
function menu_unload(type){
alert('test'); //this displays
var div = document.getElementById("menu");
div.parentNode.removeChild(div); // doesn't remove the div
document.getElementById(type).onclick = menu_load(type);
}
window.onload = function(){
menu_load('test');
}
Is there any mistake here that I have missed? I just can't work out the problem.
Your code works for me if I correct the following line:
document.getElementById(type).onclick = menu_load(type);
Which incorrectly calls menu_load() and tries to assign the result to .onclick. It should be like you did in the other function
document.getElementById(type).onclick = function() { menu_load(type); };
Demo: http://jsfiddle.net/MCZza/
To be honest I don't know why this fixes it, since your code wasn't actually a syntax error, but because it called menu_load() it recreated the div just removed. and the .removeChild() line should happen first, but anyway...

Categories

Resources