I have a banner enclosed in a div tag that contains my banner. I would like to get the banner to fade to the next image but unsure how to achieve the fading effect. I have tried using jQuery fadeIn() but it failed.
The reason why I need to use the background: url() is because I want this banner image to resize pleasantly when the browser gets resized. I am not sure if this is the best way of approaching my problem.
EDIT - My current code does swap the images in the banner, but does not apply the fadeIn() effect. The console does not report any errors.
CSS:
header div#banner {
background: url(../image/banner/00.jpg) no-repeat center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
height: 300px;
}
JavaScript:
var bannerImages = new Array();
var bannerCounter = 0;
function run() {
loadBannerImages();
runBannerTimer();
}
function loadBannerImages() {
var filePath = "image/banner/";
bannerImages[0] = filePath + "00.jpg";
bannerImages[1] = filePath + "01.jpg";
bannerImages[2] = filePath + "02.jpg";
bannerImages[3] = filePath + "03.jpg";
bannerImages[4] = filePath + "04.jpg";
}
function runBannerTimer() {
var t=setTimeout("swapBannerImage()",2000);
}
function swapBannerImage() {
$('#banner').fadeIn(1000, function() {
$('#banner').css('background', 'url(' + bannerImages[bannerCounter] + ') no-repeat center');
});
bannerCounter++;
if (bannerCounter >= bannerImages.length) {
bannerCounter = 0;
}
runBannerTimer();
}
Your setTimeout isn't correct; try the following instead:
function runBannerTimer() {
var t=setTimeout(function(){
swapBannerImage()
},2000);
}
EDIT
Here is the updated Banner Swap function:
function swapBannerImage() {
$('#banner').fadeOut('slow', function(){
$('#banner').css('background', 'url(' + bannerImages[bannerCounter] + ') no-repeat center').fadeIn('slow');
});
bannerCounter++;
if (bannerCounter >= bannerImages.length) {
bannerCounter = 0;
}
runBannerTimer();
}
Updated Demo Here
You could use multiple divs -- one per image -- and fade them in/out. The divs could still use the css background like you want, you'll just need to absolutely position them, so that they appear one on top of another. However, to get absolutely positioned divs to resize with the parent div (ie to get the "pleasant" resizing effect), you have to set up the css like so:
header div#banner {
... /* your background stuff here */
position: absolute;
left: 0;
right: 0;
height: 300px;
}
Note that you'll assign both left and right, which would make it take up the entire width of the parent. And, make sure that the parent has position:relative.
Related
I set the following CSS at the top of my file:
#img1, #img2, #img3 {
background: url("bates-sprite.jpeg");
background-repeat: no-repeat;
object-fit: none;
}
#img1 {object-position: 0 0;
width: 816px; // full size 3264
height: 612px; // full size 2448
}
This is the relevant part of my JavaScript:
var tempDiv = document.createElement('div');
tempDiv.setAttribute("id", "bigImg" + figNum);
// Make tempDiv High enough to hold the scaled up image.
// This line is causing a problem
let imgHeight = document.getElementById("img1").clientHeight;
// let imgHeight = "1224px";
tempDiv.style.height = parseInt(imgHeight) + parseInt("400px") + "px";
If I set imgHeight explicitly to 1224 pixels, the function works perfectly. If instead I use clientHeight, it fails. How can I fix it?
Client height will only give a number, but you need to add the type of that, also like (px, %, rem), to make it work.
Hi everyone I was just wondering if anyone know how to convert this css/jquery code into javascript DOM code?
I started coding my entire code using javascript DOM for a project but then I found this code which will make the background image move upwards in an infinite loop.
I just need some help in figuring out how to convert the code since I know nothing about jquery.
$(function(){
var x = 0;
setInterval(function(){
$('body').css('background-position','0'+--x + 'px');
}, 10);
})
html,body { height: 100%; overflow: hidden;}
body {
background-image: url('http://lorempixel.com/1900/1200/');
background-repeat: repeat-y;
background-size: 100% 100%;
}
html,body { height: 100%; overflow: hidden;}
body {
background-image: url('http://lorempixel.com/1900/1200/');
background-repeat: repeat-y;
background-size: 100% 100%;
}
$(function(){
var x = 0;
setInterval(function(){
$('body').css('background-position','0'+--x + 'px');
}, 10);
})
$('body') selects the body element; .css(prop, value) sets the CSS property prop to value. With the plain DOM API, you can get the body using document.body and assign styles by assigning to properties on the element’s style, noting that hyphenated-names become camelCase.
var x = 0;
setInterval(function () {
document.body.style.backgroundPosition = '0 ' + --x + 'px';
}, 10);
I am new to Javascript but I was able to piece together something to create a random background image on page load. This was successfully used for a Div object on the page.
Since this worked well, I wanted to use this command again for a second Div object on the same page. Both Divs had separate CSS style names so I thought this would be fine. However as soon as I use both commands together, only one will work.
I assumed it was an overloading problem, but I tried renaming everything I could and it still hasn't solved it. Is there something else I need to rename that I'm missing or do I need to frame the two separate commands differently?
Below is the JS code, CSS and HTML:
Thanks in advance!
/*! random background image 2*/
window.onload = function frontimage() {
var thediv2 = document.getElementById("topimg");
var imgarray2 = new Array("f1.svg", "f2.svg");
var spot2 = Math.floor(Math.random()* imgarray2.length);
thediv2.style.background = "url(img/f-img/"+imgarray2[spot2]+")";
thediv2.style.backgroundSize = "70%";
thediv2.style.backgroundAttachment = "fixed";
thediv2.style.backgroundRepeat = "no-repeat";
thediv2.style.zIndex = "2";
thediv2.style.backgroundColor = "rgba(255,204,255,0.5)";
}
/*! random background image 1*/
window.onload = function backimage() {
var thediv = document.getElementById("imgmain");
var imgarray = new Array("b1.jpg", "b2.jpg", "b3.jpg", "b4.jpg", "b5.jpg");
var spot = Math.floor(Math.random()* imgarray.length);
thediv.style.background = "url(img/b-img/"+imgarray[spot]+")";
thediv.style.backgroundSize = "100%";
thediv.style.backgroundAttachment = "fixed";
thediv.style.backgroundRepeat = "no-repeat";
thediv.style.zIndex = "1";
}
#bigimg {
clear: both;
float: left;
margin-left: 0;
width: 100%;
display: block;
}
#imgmain {
background: 50% 0 no-repeat fixed;
z-index: 1;
width: 100%;
}
#topimg {
z-index: 2;
position: absolute;
background-image: url(../img/f-img/f2.svg);
background-repeat: no-repeat;
background-position: 50% -25%;
background-size:contain;
width: 100%;
margin: auto;
padding: 0;
}
<div id="bigimg">
<section id="imgmain"></section>
<section id="topimg"></section>
</div>
With addEventListener, you can add as many event handlers as you want.
window.addEventListener('load', function frontimage() {
// ...
});
window.addEventListener('load', function backimage() {
// ...
});
You are overriding your first window.onload by reassigning the callback function.
Try this:
window.onload = function() {
frontimage();
backimage();
}
This is my code, to see it in action, take a look at this Fiddle
HTML
<div id="header">
.
.
.
</div>
CSS
#header {
background: url(images/img8681.jpg);
background-size: cover;
border-bottom: 8px solid #333333;
height: 620px;
}
Javasript (jQuery)
var imgs = new Array("images/img8681.jpg","","","","");
function changeBg() {
var imgUrl = imgs[Math.floor(Math.random()*imgs.length)];
$('#header').css('background-image', 'url(' + imgUrl + ')');
}
setInterval(changeBg,5000);
My question how can I have the change of the images smoothly instead of "just replace" ?
And how to avoid continuously appear of the same image ?
You can get a smoother change of the image if you use the fadeIn and fadeOut functions.
var imgs = new Array("img1.jpg","img2.jpg","img3.jpg","img4.jpg","img5.jpg");
function changeBg() {
var imgUrl = imgs[Math.floor(Math.random()*imgs.length)];
$('#header').css('background-image', 'url(' + imgUrl + ')');
$('#header').fadeIn(1000); //this is new, will fade in smoothly
}
function changeBackgroundSmoothly() {
$('#header').fadeOut(1000, changeBg); //this is new, will fade out smoothly
}
setInterval(changeBackgroundSmoothly,5000);
See this Fiddle to see the result.
Concerning the randomness of the images you can't do a lot if it does have to be random. Simply because random implies that the same image might appear twice in a row, otherwise it wouldn't be totally random as you could exclude one result.
A solution might be to not display the images randomly, but rather in a predefined sequence, refer to this site for an example.
Just another approach
$("#header").fadeOut(500, //Speed
function () { //On fadeOut complete
$(this).css("background-image", "url(img2.jpg)") //Change BG
.fadeIn(); //FadeIn
});
You can check here: https://jsfiddle.net/rafaelaca/wwjro184/
For whatever reason, my jquery loading overlay doesn't load at all under any circumstance even though the same code was working just days ago. Well, not the exact same code. I have been trying to get the overlay to resize with the window, and I have been trying different things, but I don't understand what I did that caused the overlay to never even show up? Here is the code that should attach to the overlay to the correct div...
function MRNSearchInternals()
{
//debugger;
var form = $("#MRNSearch");
$div = $("#TabView1");
var srlzdform = form.serialize();
var PopID = <% =PopID %>;
var options = [];
var $url = $("#target").attr("action");
$('<div id="overlay">').css({
position: 'absolute',
opacity: 0.2,
top : $div.offset().top,
left : $div.offset().left,
width : $div.offset().width,
height : $div.outerHeight(),
background: 'blue url(<%=Url.Content("~/images/ajax-loader.gif")%>) no-repeat center'
}).hide().appendTo($div);
$("#overlay").fadeIn();
$.post('<%:Url.Action("SearchByMRN", "PatientACO")%>', srlzdform, function (data)
{
DisplayDemographicSearch(data);
$("#overlay").fadeOut();
});
}
Notice how I create the div. I give it an id, and then I call it's css atribute. From there I set all the css attributes. I then attempt to call fadeIn, and fadeOut after the ajax call. Any body have any idea why this isn't working? Any help would be great.
Some More clarification
Also notice how I chose the div to overlay. I get a div id from my dom
$div = $("#TabView1");
Also, I looked the source, and I do have that particular div in there. So that is not the problem. Somehow or the other, it simply isn't showing up.
UPDATE: The DOM I get
Below is what is produced from the jquery code. It appears as though everything is being created fine. Note also, that display is set to none. That is what I would expect since I have the overlay fade out. My question is why does it never show up.
<div class="TabView" id="TabView1">
<div class="Tabs">...</Tabs>
<div class="Pages">
<div id="overlay" style="left: 114px; top: 205px; height: 452px; display: none; position: absolute; opacity: 0.2; background-image: url("/images/ajax-loader.gif"); background-attachment: scroll; background-repeat: no-repeat; background-position-x: center; background-position-y: center; background-size: auto; background-origin: padding-box; background-clip: border-box; background-color: blue;"/>
</div>
Well, the better way to create the overlay div would be
$('<div/>', {
id: 'overlay'
})
Does that solve the problem? Otherwise, the ID might not be created, or does it?
Update for the edit from your post: the "width" attribute is not set on the created overlay. What happens if that is added and set to e.g. 100px? It seems like there is something wrong with the setting of the width attribute (or the getting of the width attribute of $div).
Is this code called more than once? If so, are you removing #overlay somewhere?
Calling this code multiple times would create duplicate #overlay dom nodes which is a no-no and could explain why it doesn't work sometimes.
To remove it, change:
$("#overlay").fadeOut();
to:
$("#overlay").fadeOut('slow', function () {
$("#overlay").remove();
});
Your selector doesn't look right.
I would try:
$('#overlay').css. . . .
function MRNSearchInternals()
{
//debugger;
var form = $("#MRNSearch");
$div = $("#TabView1");
var srlzdform = form.serialize();
var PopID = <% =PopID %>;
var options = [];
var $url = $("#target").attr("action");
$('<div id="overlay">').css({
position: 'absolute',
opacity: 0.2,
top : $div.offset().top,
left : $div.offset().left,
width : $div.offset().width, //<- The problem is right here should be $div.width
height : $div.outerHeight(),
background: 'grey url(<%=Url.Content("~/images/ajax-loader.gif")%>) no-repeat center'
}).hide().appendTo($div);
$("#overlay").fadeIn();
$.post('<%:Url.Action("SearchByMRN", "PatientACO")%>', srlzdform, function (data)
{
DisplayDemographicSearch(data);
$("#overlay").fadeOut('slow', function () {
$("#overlay").remove();
});
});
}
Man. That was real hard to debugg. I wish Visual studio 2010 had better jquery debugging capability. Thankfully, the next version is supposed to be a better jquery debugger. But, the problem was the width attribute.