Assign background image from attr - javascript

I need to set different background-image to several divs. I am setting an attr that contains the path to the background image that specific div needs to use. The problem comes when I try to pull the attr into the function that sets the bg.
This isn't working but you can see what I am doing.
$('.someDiv').each(function(){
thisDataBgPath = $(this).attr('data-bg');
$(this).css('background-image', 'url(../images/' + thisDataBgPath + ')');
});
I tried background, and backgroundImage as well and neither work.
When I use a normal image path it works, but when I try to inject a variable it doesn't work.
the html is very basic
<div id="item">
<div class="" data-bg="section-bg-large-career-1.jpg"></div>
<div class="" data-bg="section-bg-large-career-2.jpg"></div>
<div class="" data-bg="section-bg-large-career-3.jpg"></div>
</div>

Works for me. You might have an incorrect path? Here's a quick test with your code. I just removed the ../images part since I'm not testing a local image.
http://jsfiddle.net/DvNjA/
$('.someDiv').each(function(){
thisDataBgPath = $(this).attr('data-bg');
$(this).css('background-image', 'url(' + thisDataBgPath + ')');
});

Related

I want to ask a question about javascript image src

<img src="../1.jpg" alt="" id="change-image">
<button id= "press-to-change">Press</button>
let count = 0;
let arr = ["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"]
document.getElementById("press-to-change").addEventListener("click", function(){
count++;
document.getElementById("change-image").src = "../" + arr[count]
So we have an HTML with an image and a button and in JS we have an array with images and we want to change the src of the image when we press the button(this is only a part of the code)
The above code works fine but i have a question why with:
document.getElementById("change-image").src = "../" + arr[count] code works fine but with document.getElementById("change-image").src = `url('../${arrImage[count]}')` code doesn't work.
For example this next code from another project works perfectly imageContainer.style.backgroundImage = `url('../${arrImage[count]}')`
background-image is a for style of an element and uses css format.
src is for the actual source of the image element and requires a valid path only
With images, you use or assign to the src property only for <img> elements.
If you want to set the background image of an arbitrary (but non-<img>) element, you need to use different syntax: you have to assign to the style.backgroundImage property, and you have to surround the URL you're setting with url(...)
The rendered HTML markup looks like this:
<img src="foobar.png">
<div style="background-image: url('foobar.png');"></div>
They're not interchangeable. With the background-image property, you need to always use url(...). With the src attribute, you need to never use url(...).
The text: url(image.jpg) is syntax only used in CSS.
That’s why it works for backgroundImage but not src
An image will always need src="path/to/image.jpg" without url() surrounding it.

Using custom attr to add css?

I'm using a generic CSS banner code with a little CSS3 animation (Not the point, but providing background). What I'm trying to achieve is setting the banner class with a custom attribute and getting that attributes content and using jQuery to append a style with it? Like so, However their is alot of these divs that will be using the same technique on the same page...
<div class="banner banner-small animate" data-bg="https://domain.com/path/img/bg.png">
....
</div>
Then jQuery would run and output the code like...
<div class="banner banner-small animate" data-bg="https://domain.com/path/img/bg.png" style="background-image: url('https://domain.com/path/img/bg.png')">
....
</div>
I hope that this wasn't to vague. I've only recently started learning jQuery and I'm loving it! Just don't really know how to go around doing this.
Sure, there are a variety of ways that you can use data attributes as selectors and then access their data via the data() function :
// Iterate through each element with the data-bg attribute
$('[data-bg]').each(function(){
// Set the background image for each element to it's respective
// attribute value
$(this).css('background-image','url(' + $(this).data('bg') + ')');
});
Or if you don't want to invoke jQuery twice, you can use Niet's suggestion:
$('[data-bg]').each(function(){
this.style.backgroundImage = url(' + this.getAttribute('data-bg') + ')';
});
Or the following one from adeneo, which forgoes an explicitly loop entirely:
$('[data-bg]').css('background-image', function() {
return 'url(' + $(this).data('bg') + ')';
});

How to replace div background with whichever img src comes next in the DOM?

I have this header on about 400 pages:
<div class="header">
</div>
Then later on down in the HTML there will inevitably be an image, eg:
<img src="image.png" />
What I want to do is have JS or JQuery search down the markup for the very next img tag that appears, and replace the header with:
<div class="header" style="background-image:image.png">
</div>
Is this even possible? This Stack question has a way of getting the next image: how to get the next image tag after specific dom tag, sibling or not? but I cannot figure out how to set that image as the background, as per the desired result above.
jQuery has .css() which will allow you to specify a CSS property value.
elem.css('background-image', url); will do the trick.
But the vanilla JS way to do it is with elem.style.backgroundImage = url;
You can do with :first jQuery selector.
$(document).ready(function () {
$('.header').css('background-image', $('.header img:first').attr('src'));
});
This is how I did it:
$(".header").each(function() {
$(this).css('background-image', 'url(' + $(this).next('img').attr('src') + ')');
});
Here is the JSFiddle demo

Image swapping with Jquery

I am very new to Jquery so please excuse this noobie question. I am trying to swap a background image of an <h1> element when a user clicks on the corresponding hyperlink. The <a> tags are generated dynamically and there can be 'n' quantity of them at any time depending on how many images are set in a SQL table.
My HTML is:
<div id="feature-image">
<h1><span>A random heading</span></h1>
</div>
<div id="feature-links">
<a class="a1" href="#">1</a>
<a class="a2" href="#">2</a>
<a class="a3" href="#">3</a>
</div>
The <span> tags are set to display:none
I've written this Jquery statement to run when a user clicks on a hyperlink in the #feature-links div. I was attempting to set the var image to the name of the <a> tags class (a1, a2, a3) etc. and then change the CSS background image property of the <h1> using the image var as part of the .jpg. url.
<script>
$(function(){
$('#feature-links a').click(function(){
var image = $(this).attr("class","");
$('#feature-image h1').css('background-image','url=(\'main_' + image + '.jpg\')');
});
});
</script>
all my images are named "main_a1.jpg", "main_a2.jpg" and so on...
I can't see what I am doing wrong or whether what I am attempting to do (grab class names etc. in vars) is actually good practice or not... some help would be really appreciated.
Thanks in advance!
EDIT:
Jquery code after edits:
$(function(){
$('#feature-links a').click(function(){
var image = $(this).attr('class');
$('#feature-image h1').css('background-image','url(images/main_' + image + '.jpg)');
});
});
Change line to:
var image = $(this).attr("class");
I believe specifying 2 parameters to the .attr() function is used for changing the attribute value. Therefore in your case, it would change the class to "".
Specifying one parameter will return the value of the class
A better way, instead of using the class would be to set the href.
For example:
$('#feature-links a').click(function(e){
$('#feature-image h1').css({
'background-image': 'url(' + $(this).attr('href') + ')'
});
e.preventDefault(); // Stops the standard link behaviour
});
Then your links would simply link directly to the background image:
1
Hope that helps :)

How to use jquery with variable assigned

How can I use a variable in jQuery. as you see in script snippet, I assign a variable "divname" with value, and when i use 'Jquery" to fade out. it is not working. What I really need is, when image is hover, the description will be show up as fading in, when mouse is gone, the the description should be gone. thanks in advance.
Script snippet
$j('.img_nofade').hover(function(){
$j(this).animate({opacity: .5}, 300);
var i = $j(this).attr('titlename');
var divname = "'#titleID" + i + "'";
//alert (divname);
$j(divname).fadeIn();
},
function(){
$j(this).animate({opacity: 1}, 300);
$j(divname).fadeOut();
}
);
HTML code
<img class="img_nofade' src="image-1.gif" titleid='1" />
<div id="titleID1">my image title 1 </div>
<img class="img_nofade' src="image-2.gif" titleid='2" />
<div id="titleID2">my image title 2 </div>
<img class="img_nofade' src="image-3.gif" titleid='3" />
<div id="titleID3">my image title 3 </div>
No need to use the ' char, just:
var divname = "#titleID" + i;
And in the hover's handlerOut function, the divname is already out of scope, you should define it again.
There are a few issues I see.
Your attributes in your HTML are mixing single and double quotes. You need to use one or the other.
$j(this).attr('titlename'); - The attribute name doesn't match your HTML attributes. (titlename vs titleid)
You have a scoping issue with the var divname. You define it in your mouseover event which means it won't be defined in your mouseleave event. You should just use the next method to get a reference to your div. $j(this).next().fadeIn() This would prevent the need for trying to find the titleID in the first place.
There are a few issues here.
1) You have some typos in the HTML. Be careful about single and double quotes. Not all browsers will automatically correct those kinds of errors, and if Javascript can't find the HTML it's looking for, then your code will break.
2) jQuery provides some excellent resources for getting elements without having to fall back on the varname-style thing (i.e. var titleId = $(this).attr('titleId')+i;)
Instead, you can do something like this:
<img class="img_nofade" src="image-1.gif"/>
<div class="description">my image title 1 </div>
<img class="img_nofade" src="image-2.gif"/>
<div class="description">my image title 2 </div>
<img class="img_nofade" src="image-3.gif"/>
<div class="description">my image title 3 </div>
I got rid of the titleId attribute and changed the divs from id="TitleID1" to "description". It's more generic, but it's also more semantic from a styling standpoint. You won't have to individually style each of those things.
The jQuery would look something like:
$('.img_nofade').hover(function(){
$(this).animate({opacity: .5}, 300);
$(this).next('.description').animate({opacity: 0}, 300);
},function(){
$(this).animate({opacity: 1}, 300);
$(this).next('.description').animate({opacity: 1}, 300);
});
The $.next() method grabs the next element. If you pass in a selector, you can grab the next element with that selector. This is really useful when you're dynamically adding things to the page and want to grab the next one on the list. There are several other ways to do this, this just happens to be the easiest in this scenario, I think.
Finally, you should keep in mind that the .fadeIn() and .fadeOut() methods will change the display attribute to display:none when hiding. This means that in your above example, without any styling, the titles would disappear, causing the images to slide together. That's why I chose to animate on the opacity instead. You can definitely do the fadeIn/fadeOut thing if you have CSS styling those images to keep them from collapsing in on each other.
Good luck.
You have two functions for the hover and have declared divname in the first and then you are trying to use it in the second. This won't work because it is not in scope of the second function.
Instead of using the divname in this case you could use $j(this).next() to select the next sibling, in this case the div following the img and call fadeIn() and fadeOut() that way.
$j('.img_nofade').hover(function(){
$(this).next().fadeIn();
}, function(){
$(this).next().fadeOut();
});
This isn't too hard
$j('.img_nofade').hover(function(){
var title = 'titleID' + $(this).attr('titleid');
$('#' + title).fadeIn();
}, function(){
var title = 'titleID' + $(this).attr('titleid');
$('#' + title).fadeOut();
});
Try this fiddle
http://jsfiddle.net/cmyks/

Categories

Resources