Background-image style attribute in JavaScript - javascript

I'm trying to apply a background image using a style tag on a div that's reference in JavaScript. I'm sure it's something to do with the quotations around the image variables. Any help would be greatly appreciated.
function appendData () {
var image = "http://domain.com/image.jpg";
var html = '<div class="itemImage" style="background-image:url(' + image + ');"></div>';
$('.container').append(html);
}

I would consider changing your approach slightly. Sure, you can append the html to your container OR you could change the property of the itemImage without re-writing it every time.
If you build the itemImage div into that container you could do this instead
function appendData () {
var image = "http://domain.com/image.jpg";
$(".itemImage").css("background-image", image);
}

function appendData () {
var image = "http://domain.com/image.jpg";
var html = '<div class="itemImage" style="background-image:url(\'' + image + '\');"></div>';
$('.container').append(html);
}

Related

extract div as HTML including CSS classes

I am trying to create a general function that will extract a div content (with nested elements) and save it locally in an HTML file.
Basically I get the div innerHTML, wrap it in html/head/body tags and then save it:
function div2html() {
var inner=document.getElementById("div2save").innerHTML;
var html="<html><head></head><body>"+inner+"</body></html>";
saveTextAsFile("div2html.html", html);
}
See a working version here: jsfiddle
However I am not sure how to handle classes. As you can see the class in the sample (bigbold) is not embedded in the new HTML. I need some way to get all the classes used in the div and then add them (or the computed styles ?) to the html I generate .. is this possible ? is there any other way around it ?
Try including style element .outerHTML within saved html
function div2html() {
var inner=document.getElementById("div2save").innerHTML;
var style = document.getElementsByTagName("style")[0].outerHTML;
var html="<html><head>"+style+"</head><body>"+inner+"</body></html>";
saveTextAsFile("div2html.html", html);
}
jsfiddle http://jsfiddle.net/fb6s763w/1/
Alternatively, using window.getComputedStyle() to select only css of #div2save child node
function div2html() {
var inner = document.getElementById("div2save");
var style = window.getComputedStyle(inner.children[0]).cssText;
var html = "<html><head><style>"
+ "." + inner.children[0].className
+ "{" + style + "}"
+ "</style></head><body>"
+ inner.innerHTML + "</body></html>";
saveTextAsFile("div2html.html", html);
}
jsfiddle http://jsfiddle.net/fb6s763w/2/
Looks like this might be able to help you out:
https://github.com/Automattic/juice
If the CSS of the page is not big, a simple solution is to include it all in the saved html as suggested by guest271314 above with
var style = document.getElementsByTagName("style")[0].outerHTML;
see jsfiddle
A more comprehensive solution extracts the classes from the div and then adds only the rules of those classes to the div (Using code from How do you read CSS rule values with JavaScript?)
function div2html(divId) {
var html = document.getElementById(divId).innerHTML;
// get all css classes in html
var cssClasses = [];
var classRegexp = /class=['"](.*?)['"]/g;
var m;
while ((m = classRegexp.exec(html))) cssClasses = cssClasses.concat(cssClasses, m[1].split(" "));
// filter non unique or empty cssClasses
cssClasses = cssClasses.filter(function (item, pos, self) {
return item && self.indexOf(item) == pos;
});
// get html of classes
var cssHtml = '';
for (var i = 0; i < cssClasses.length; i++) cssHtml += getRule('.' + cssClasses[i]);
// assemble html
var html = "<html><head><style>" + cssHtml + "</style></head><body>" + html + "</body></html>";
console.log(html);
saveTextAsFile("div2html.html", html);
}
see jsfiddle

Replacing an image with another in jquery using classes and IDs

I understand that this question has been answered before, but even after consulting those links, I am still unable to solve my problem. I want to replace my image (assets/img/social-mail.jpg) to another (assets/img/social-mail-hover.jpg), with a single class, because I have multiple images I would like to do this to. My basic thought process is this: When the class is hovered, take the ID, and replace its image with another by adding "-hover" to its image link.
HTML:
<img id="social-mail" class="box-social" src="assets/img/social-mail.jpg">
JS:
$(".box-social").hover(function(e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "img/social-" + icon + "-hover.jpg";
$(id).find("img").attr("src", image);
});
I've tested id, icon, and image; and they all give me exactly what I want. However, when I hover over the image, it still isn't being replaced. I'm not getting any errors either. What am I doing wrong? Thank you so much!
I think there are at least four problems with your function:
To select by element id you need the # prefix, so $("#" + id) not $(id).
You don't want .find() because this is already the image in question.
Your image path in the html begins with "assets" but you don't include that in your Javascript.
If you only supply one funtion to .hover() that function will be called both when the mouse moves in and when it moves out. So you never change the image back.
The four lines of your function can be replaced with one line:
$(".box-social").hover(function(e) {
this.src = "assets/img/" + this.id + "-hover.jpg";
});
This fixes problems 1-3 above. To fix problem 4 just supply a second function to change the src back when the mouse leaves:
$(".box-social").hover(function(e) {
this.src = "assets/img/" + this.id + "-hover.jpg";
}, function(e) {
this.src = "assets/img/" + this.id + ".jpg";
});
You need to correct your selector.
JS:
$(".box-social").hover(function (e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "assets/img/social-" + icon + "-hover.jpg"; //make sure the path is correct
$('#' + id).attr("src", image); //Changed the selector.
});
Demo:http://jsfiddle.net/GCu2D/521/
try this
$(".box-social").hover(function(e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "assets/img/social-" + icon + "-hover.jpg";
$("#"+id).attr("src", image);
});
you forgot "assets/" in your image link and your img selector is not corresct

Show image in JavaScript

I got a litlle js code that is showing me updates from a feed
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://google.com/");
feed.setNumEntries(1);
var count = 1;
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
var html = "";
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
html = "<h5>" + count++ + ". <a href='" + entry.link + "'>" + entry.title + "</a></h5>";
var div = document.createElement("div");
div.innerHTML = html;
container.appendChild(div);
}
document.write(html);
}
});
}
google.setOnLoadCallback(initialize);
What i want to do is to show the first image from the posts from the feed. i would also like to have the title so entry.title and entry.content
Even though parsing html with regx is big dodo, I will still advise you this, parse your content html with /<img\s+src\s*=\s*(["'][^"']+["']|[^>]+)>/
Or a lazy way is to have a hidden div and do this
var temp = document.createElement( 'div' );
temp.innerHTML = html_str;
var images = temp.getElementsByTagName( 'img' );
First, you must use entry.content instead of entry.title in order to get the full HTML content of the entry. You may have something like this:
var content = entry.content;
var imgArray = content.match( /<img\s+src\s*=\s*(["'][^"']+["']|[^>]+)>/ );
// imgArray[0] would contain the first image (more likely the one that better describe the post)
P.S.: I didn't steal this Regex from actual answer, but it seems that we've got to the same reference for it :-)
UPDATE:
Then, to display it in a container, I would advise you to dynamically create DOM elements to gain more control over it, and in which you will be able to easily associate a value. Something like this:
var dom_h5 = document.createElement('h5');
var dom_entryTitle = document.createElement('div');
dom_entryTitle.className = 'title-classname';
dom_entryTitle.innerHTML = entry.title;
dom_h5.appendChild(dom_entryTitle);
container.appendChild(dom_h5);
To simplify the image part, you could create a separate div and inject the image tag as his innerHTML.
This may help you:
Web API Reference - document.createElement

javascript to enlarge img

I've got some problems while trying to change the size of an image when 'mouseover' occurs.
I know it can be done by css, but I need to realize it by js.
JS Codes:
// id is passed to this function.
...
var content = document.getElementById("content");
var li;
// generate lists of img from db.
li = document.createElement("li");
li.innerHTML = '<img src="' + id + '" />';
content.appendChild(li);
addDomListener(li, 'mouseover', function(){
li.style.height = '600px';
li.style.width = '800px';
});
HTML codes:
<div>
<ul id="content">
</ul>
</div>
seems right, but it doesn't work. I suspect the problem is 'li.style.height'. Could anyone tell me the correct way to realize it? Thx!
You were changing the height and width of li element itself, instead of the img element, for that replace your following code:
li.style.height = '600px';
li.style.width = '800px';
for this one:
li.firstChild.style.height = '600px';
li.firstChild.style.width = '800px';
You are changing the dimensions of the li element, not the image itself, so the behaviour is expected. You need to get a pointer to your image first.
In addition, you should use jQuery for manipulating the DOM and modifying an element's style on a mouse event. It will make your like much easier.
Change the size of the <img>, not of the <li>:
var li = document.createElement("li");
var img = document.createElement("img");
img.src = id;
li.appendChild(img);
content.appendChild(li);
addDomListener(li, 'mouseover', function(){
img.height = '600px';
img.width = '800px';
});

change image of img tag using innerhtml

i want to change image using innerhtml of img tag when i click on it my code is given below
tempData +='<td >';
tempData +='<img src="'+frontImg+'" id='+ii+' onClick="flipImage(this.id);" />';//from where flipImage call
tempData +='</td>';
it works fine but it change image when it return form the function but i wanted to change it before flipImage return
function flipImage(m)
{
var jsonLen = jsonImages.images.length;
var imgNumber = finalImageArray[m];
for(jsn = 0;jsn <jsonLen ;jsn++)
{
if(jsonImages.images[jsn].imageKey== imgNumber)
{
realImage = jsonImages.images[jsn].imagePath;
var element = document.getElementById(m);
// var mg = '<img src="bool.jpg" />'; // change when this line execute what should i put here.?
//element.innerHTML=mg; want like this.
//this is actual code but it change image after returning the function so i don't want this.
element.innerHTML=realImage;
element.setAttribute('src',realImage);
element.setAttribute('onclick', '');
break;
}
}
}
so i wanted to change image before flipImage return.
this is just a sample code and
You can't use innerHTML for <img /> tags as they don't have HTML inside them, they're singletons and have no inside contents.
Just use imgElement.setAttribute('src', 'http://...'); to change the image.

Categories