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') + ')';
});
Related
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 + ')');
});
I want to change display without documentGetElementById if possible but the following is not working.
html
Instructions<div id="showfaq1" style="display:none;">Open Box. Remove device. </div>
javascript:
function toggleFaq(faqid) {
//alert(faqid);
var divname = "showfaq"+faqid;
//alert(divname);
divname.style.display="block";
}
Can anyone tell me what I am doing wrong?
Thank you.
I can't get why you do not want to use getElementById, but...
If you have elements in order like this
Instructions
<div id="showfaq1" style="display:none;">Open Box. Remove device. </div>
Instructions
<div id="showfaq2" style="display:none;">Open Box. Remove device. </div>
...
Instructions
<div id="showfaqN" style="display:none;">Open Box. Remove device. </div>
You may use
Instructions
function toggleFaq(obj) {
obj.nextElementSibling.style.display = 'block';
}
In your code divname is a variable containing a string "showfaq1", which doesn't have style property.
To change the style of an element you need a reference to that element which you can obtain using document.getElementById(divname):
function toggleFaq(faqid) {
//alert(faqid);
var divname = "showfaq"+faqid;
//alert(divname);
document.getElementById(divname).style.display="block";
}
If you have an allergy to document.getElementById, you may use document.querySelector('[id="' + divname +'"]');, but its support is not as good as the former, and it's slower.
Posting a separate answer as it has no impact on my previous one. But you could make the base mechanism without JS at all, then use one of the JS-based solutions to fix it in broken browsers if needed:
HTML
Instructions
<div id="showfaq1">Open Box. Remove device. </div>
CSS
a + div { display:none; }
a:focus + div, a + div:target { display:block; }
DEMO
$('.email').each(function(l,i){
var that = $(this);
var thatOtherOne = $(this:after);
$('<a>').attr('href', 'mailto: '+ that.html + thatOtherOne.css('content')).insertAfter(that);
that.hide();
});
.email:after {
content: "#mydomain.com";
}
<span class="email">info</span>
Hello again Stackoverflow!
This is my method against spam. Using CSS the :after selector and content I try fill my custom email in inside the <span> and the css adds the url. This doesn't make it clickable though, so that's why I try the above method using JS/jQuery.
This sadly doesn't work because $(this:after); is not a valid selector. How can I change this?
You simply cannot construct a selector like that; it really doesn't make syntactic sense. Selectors are for searching through the DOM. To do what you're trying to do, you can try using the attr() trick in your "content":
.email:after {
content: attr(data-domain);
}
Then in your markup:
<a class=email data-domain='#whatever.com'>info</a>
And your JavaScript can then do this:
$('.email').each(function(l,i){
var that = $(this);
var domain = that.data('domain');
$('<a>').prop('href', 'mailto: ' + that.text() + domain).insertAfter(that);
that.hide();
});
The idea is to keep stuff that your code actually needs to use in a separate attribute, and then use the attr() operator (or whatever you want to call it) in the CSS rule to get that attribute value and use it as content. The operator can be combined with strings if you like. Chris Coyier has a good blog post about it.
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/
I am loading JSON data to my page and using appendTo() but I am trying to fade in my results, any ideas?
$("#posts").fadeIn();
$(content).appendTo("#posts");
I saw that there is a difference between append and appendTo, on the documents.
I tried this as well:
$("#posts").append(content).fadeIn();
I got it, the above did the trick!
But I get "undefined" as one of my JSON values.
If you hide the content before you append it and chain the fadeIn method to that, you should get the effect that you're looking for.
// Create the DOM elements
$(content)
// Sets the style of the elements to "display:none"
.hide()
// Appends the hidden elements to the "posts" element
.appendTo('#posts')
// Fades the new content into view
.fadeIn();
I don't know if I fully understand the issue you're having, but something like this should work:
HTML:
<div id="posts">
<span id="post1">Something here</span>
</div>
Javascript:
var counter=0;
$.get("http://www.something/dir",
function(data){
$('#posts').append('<span style="display:none" id="post' + counter + ">" + data + "</span>" ) ;
$('#post' + counter).fadeIn();
counter += 1;
});
Basically you're wrapping each piece of the content (each "post") in a span, setting that span's display to none so it doesn't show up, and then fading it in.
This should solve your problem I think.
$('#content').prepend('<p>Hello!</p>');
$('#content').children(':first').fadeOut().fadeIn();
If you are doing append instead then you have to use the :last selector instead.
You have to be aware that the code doesn't execute linearly. The animated stuff can't be expected to halt code execution to do the animation and then return.
commmand();
animation();
command();
This is because the animation uses set timeout and other similar magic to do its job and settimeout is non-blocking.
This is why we have callback methods on animations to run when the animation is done ( to avoid changing something which doesn't exist yet )
command();
animation( ... function(){
command();
});
$(output_string.html).fadeIn().appendTo("#list");
assuming you have the following in the css defined:
.new {display:none}
and the javascript should be :
$('#content').append('<p class='new'>Hello!</p>');
$('#content').children('.new').fadeIn();
$('#content').children.removeClass('new');
$('#content').children('.new').hide();
First is convert received data to jQuery Object.
Second, hide it immediately.
Third, append it to a target node.
And, after this all, we can clearly use necessary animation, just like fadeIn :)
jNode = $("<div>first</div><div>second</div>");
jNode.hide();
$('#content').append(jNode);
jNode.fadeIn();
im have a exprensive,for this:
$("dt").append(tvlst.ddhtml);
$("dd:last").fadeIn(700);
I tried what you said did the trick but is not working.
it worked with the following code
$("div").append("content-to-add").hide().fadeIn();