I want the background full image on div id="img" to change whenever the page is reloaded, can this be done on pure css or javascript is required?. Here is my http://jsfiddle.net/9Dp2e/ I am using javascript with jquery to change the background image randomly, but I doesn't work using the code below, any help would be appreciated.
Here is my html:
<div id="header">
<ul>
<div id="wrapper">
<li class="logo"></li>
<li>Homes</li>
<li>Offices</li>
<li>Products</li>
<li></li>
<li></li>
</div>
</ul>
</div>
<div id="center">
<div id="slider">
<div id='footercopy'>
<p>Copyright 2014  </p>
</div>
<div id="img">
<img src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Flaming_cocktails.jpg">
</div>
</body>
</html>
Here is my css:
html,body
{
height:100%;
}
body
{
font-family: 'Open Sans Condensed', sans-serif;
}
h1
{
font-size:30px;
}
#img
{
position: fixed;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
}
#img img
{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
min-width: 50%;
min-height: 50%;
}
#center
{
position:relative;
z-index:10;
top:0;
min-height:1000px;
background:white;
width:960px;
margin-right:auto;
margin-left:auto;
min-height:1000px;
padding:20px;
}
#header
{
position:relative;
z-index:20;
color:white;
position:fixed;
top:0;
width:1700px;
margin-right:auto;
margin-left:-10px;
background:silver;
opacity:0.7;
}
#wrapper
{
width:960px;
margin-right:auto;
margin-left:auto;
}
#header li
{
display:inline;
padding-right:20px;
}
.logo
{
font-family: 'Lobster', cursive;
font-size:30px;
color:blue;
}
/*content*/
#content
{
padding-top:80px;
width:500px;
}
.floatLeft
{
float:left;
margin: 4px;
}
.floatRight
{
float: right;
margin: 4px;
}
#content img
{
width:100px;
height:100px;
padding:20px;
}
.width
{
width:250px;
padding:10px 30px;
}
#sidebar
{
margin-top:50px;
float:right;
min-height:1500px;
text-align:center;
}
#sidebar img
{
width:150px;
height:150px;
}
#sidebar li
{
list-style:none;
padding:10px;
}
#content-right
{
padding-top:80px;
width:450px;
float:right;
}
#content-right img
{
width:100px;
height:100px;
padding:20px;
}
Here is my javascript:
var images = ['http://acdutyfree.com/images/Page95_LiquorAndTobacco_BombaySapphire_DistilledLondonDryGin_800x800.jpg', 'http://images.china.cn/attachement/jpg/site1007/20130621/0013729929f1132dee4303.jpg', ];
$('#header').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'});
$('<img src="http://acdutyfree.com/images/Page95_LiquorAndTobacco_BombaySapphire_DistilledLondonDryGin_800x800.jpg' + images[Math.floor(Math.random() * images.length)] + '">').appendTo('#img');
You can use this... Works Perfectly fine. Just made it up :)
This one is without jQuery. No need to load the heavy script in your page :)
//You can increase the images by adding more links to the array
var array = ['http://acdutyfree.com/images/Page95_LiquorAndTobacco_BombaySapphire_DistilledLondonDryGin_800x800.jpg','http://images.china.cn/attachement/jpg/site1007/20130621/0013729929f1132dee4303.jpg'];
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
var shuffled_images = shuffle(array);
var yourbackground = document.getElementById('img');
yourbackground.style.backgroundImage = 'url(' + shuffled_images[0] + ')' ;
LINK it was working with your logic , just add jquery in fiddle and increase the number of images and removed the unwanted just to check.
Math.random() between 1 and 0, will have less probability to act like random since we have only two values
Check out this tutorial: http://briancray.com/2009/12/28/simple-image-randomizer-jquery/
Start with an array of images.
Change the image filenames in the array to the actual filenames. Don't include the directory—filenames only.
<i>This is not italic</i>, and [this is not a link](http://example.com)var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];
Set a random background with jQuery and CSS background-image
$('#body').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'});
Try Using :
Here ,you have to use,
Math.random() with in Math.round() because,Math.round() figures your returning value to 0 and 1,so if you have only two images then Math.round() performed them well,and may not repeat any background more then once.
var images = ['http://acdutyfree.com/images/Page95_LiquorAndTobacco_BombaySapphire_DistilledLondonDryGin_800x800.jpg', 'http://images.china.cn/attachement/jpg/site1007/20130621/0013729929f1132dee4303.jpg', ];
var random = Math.round((Math.random()*images.length))
$('#background').css({'background-image':images[random]})
Try to bind 'beforeunload':
$(window).bind('beforeunload',function(){
/* change background */
});
How can you do this reading image from array of images?
read cookie value (a counter): if there is no value, save in it 0 value.
read images[count]
on 'beforeunload' save in coockie count+1 (if count > images.length -> count=0)
Related
I am creating an image slider and using a JavaScript timer to advance to the next picture. When the user clicks on the forward or back button (see picture below) the time the slide is displayed decreases greatly. I need help making the buttons advance the slide and reset the timer and the same time. I am attaching my JavaScript, HTML, and CSS to cover my code thoroughly.
My JavaScript:
var imageShown = 1;
var total = 7;
function autoplay() {
var image = document.getElementById('picture');
imageShown = imageShown + 1;
if(imageShown > total){imageShown = 1;}
if(imageShown < 1){imageShown = total;}
picture.src = "Images/img"+ imageShown +".jpg";
console.log("Pic Changed");
}
window.setInterval(autoplay, 5000);
function pic(x) {
var image = document.getElementById('picture');
imageShown = imageShown + x;
if(imageShown > total){imageShown = 1;}
if(imageShown < 1){imageShown = total;}
picture.src = "Images/img"+ imageShown +".jpg";
console.log("Button clicked");
window.clearInterval(autoplay);
window.setInterval(autoplay, 5000);
}
My HTML:
<img src="Images/img1.jpg" id="picture" >
<div class="left_div"><img onClick="pic(-1)" class="left_click" src="Images/left.png"></div>
<div class="right_div"><img onClick="pic(+1)" class="right_click" src="Images/right.png"></div>
</div>
My CSS:
margin:0px;
}
#imageslider {
height:700px;
width:1000px;
margin: 50px auto;
position:absolute;
border-radius:4px;
overflow:hidden;
padding-right: 5000px;
padding-top: 1000px;
}
#picture {
height:750px;
width:1000px;
position:relative;
padding-top: 50px
}
.left_div {
height: 750px;
width: 150px;
position: absolute;
top: 250px;
left: 0px;
}
.right_div {
height: 750px;
width: 150px;
position: absolute;
top: 250px;
right: 0px;
}
.left_click {
height:50px;
width:50px;
position:absolute;
top:40%;
left:20px;
opacity:0;
transition: all .2s ease-in-out 0s;
}
.right_click {
height:50px;
width:50px;
position:absolute;
top:40%;
right:20px;
opacity:0;
transition: all .5s ease-in-out 0s;
}
.left_div:hover .left_click {
opacity:0.6;
}
.right_div:hover .right_click {
opacity:0.6;
}
.left:hover .left1
You should use clearInterval as following:
clearInterval(autoplay);
or as
window.clearInterval(autoplay);
I think that you might be trying to reset the interval incorrectly
http://www.w3schools.com/jsref/met_win_clearinterval.asp this gives an example of how to reset a function set to an interval in javascript
I have loading bar in specific div, that is 700px from top of the page. JavaScript for loading bar is working fine, but it is triggered at the start page, and when I reach to specific div, bar is already loaded, what I want is to start loading when I reach to that div. Please, help.
JavaScript:
<script>
$('.numberprogress[data-percentage]').each(function () {
var progress = $(this);
var percentage = Math.ceil($(this).attr('data-percentage'));
$({countNum: 0}).animate({countNum: percentage}, {
duration: 5000,
easing:'linear',
step: function() {
// What todo on every count
var pct = '';
if(percentage == 0){
pct = Math.floor(this.countNum) + '%';
}else{
pct = Math.floor(this.countNum+1) + '%';
}
progress.text(pct) && progress.siblings().children().css('width',pct);
}
});
});
</script>
HTML:
<div class="middle>
<div class="progress"><div class="numberprogress" data-percentage="80"></div>
<div class="progressbar"><div class="progresspercent"></div></div></div>
</div>
CSS:
.progress{
float:left;
width:300px;
height:50px;
color:#FFF;
background-color:#38B1CC;
margin-top:5px;
border-radius:4px;
font-family: sans-serif;
text-align:center;
font-size:0.8em;
}
.numberprogress{
float:left;
height:18px;
width:18%;
color:white;
font-size:14px;
text-align:center;
background: rgba(0,0,0,0.13);
padding: 9px 0px;
border-radius:4px;
margin:5px;
}
.progressbar{
margin-left:0px;
float:right;
border-radius:10px;
margin:5px;
height:10px;
width:75%;
background: rgba(0,0,0,0.13);
margin-top:18px;
overflow: hidden;
}
.progresspercent{
height:100%;
float:left;
background-color:white;
border-radius:10px;
}
.middle{
height:600px;
width:auto;
font-family:Bizon;
}
Instead of load it on DOM ready or onload event, you should load it when it reach that specific div.
if ($(document).scrollTop() >= $('.target-div').offset().top) {
Your function
}
To add on #Syahrul answer, here is a working example:a working example
$(document).scroll(function () {
$('.numberprogress[data-percentage]').each(function () {
if ($(document).scrollTop() >= $(this).offset().top) {
animateProgress($(this));
}
});});
I've been messing around with my slider and I got it to slide by itself. The problem is, there is no way you can manually view the slides. I would like to add navigation dots on the bottom so you can skim through the slides without having to view them as the slider goes along. If you could help me with this it would be greatly appreciated.
My slider html:
<div id="slider-container">
<div style="position: relative">
<div class="slide"><img id="slide_1" src="images/slide_1.jpg"/></div>
<div class="slide"><img id="slide_2" src="images/slide_2.jpg"/></div>
<div class="slide"><img id="slide_3" src="images/slide_3.jpg"/></div>
<div class="slide"><img id="slide_4" src="images/slide_4.jpg"/></div>
<div class="slide"><img id="slide_5" src="images/slide_5.jpg"/></div>
<div class="slide"><img id="slide_6" src="images/slide_6.jpg"/></div>
</div>
</div>
My slider css:
.slide-container {
display:block;
}
.slide {
top:0;
width:760px;
height:420px;
display:block;
position:absolute;
transform:scale(0);
transition:all .7s;
}
.slide img {
width:100%;
height:100%;
border-radius:6px;
border:1px solid #95ca1a;
}
My slider javascript:
$(document).ready(function() {
(function (){
var count = $(".slide > img").length;
var current = 1;
var sliderNext = 2;
$("img[id^='slide_']").fadeOut(0);
$("#slide_" + current).fadeIn(300);
var loop = setInterval(function() {
$("#slide_" + current).fadeOut(300);
$("#slide_" + sliderNext).fadeIn(300);
(sliderNext >= count) ? sliderNext = 1 : sliderNext++;
(current >= count) ? current = 1 : current++;
}, 3000)
})()
});
Here's an example of what I mean by nav dots:
CSS Slider - Codepen
First create list of dots, you can do it manually by creating list of "li" tags or can create it via jQuery.
here is code
<ol>
<li></li>
<li></li>
<li></li>
</ol>
number of "li" element should match with number of images
then have following css
#slider-container {
position:relative;
overflow:hidden;
width:100%;
height:380px;
display:inline-block;
}
.slide {
top:0;
width:100%;
display:inline-block;
}
.slide img {
width:100%;
height:100%;
border-radius:6px;
border:1px solid #95ca1a;
}
/******* css of dots ****/
ol{
list-style= none;
width:100%;
}
ol li{
background: #888;
border-radius: 50%;
display: inline-block;
width:20px;
height:20px;
cursor: pointer;
}
then add following jQuery stuff
$('ol li').bind('click', function(){
var index = $(this).index() + 1;
$(".active").fadeOut(300);
$("#slide_" + index).fadeIn(300);
$(".slide").removeClass("active");
$("#slide_" + index).addClass("active");
});
this code will hide active image and shows selected image
here is Fiddle example
hope it will help you
Here is a carousel script I wrote for a project. This allows you to click forward and backward and also on the dots. It's also dynamic so if you have 1 image, there are no dots or scroll bars, if you have 2 images there are the bars to go right and left but no dots, once you have three or more images the dots will be applied.
JsFiddle
HTML
<div class="carousel-container">
<div class="left-arrow"></div>
<div class="right-arrow"></div>
<div class="carousel-image-holder">
<img src="http://digitaljournal.com/img/8/7/8/4/4/i/1/1/7/o/ulingan_kids.jpg" />
<img src="http://freethoughtblogs.com/taslima/files/2012/06/22-funny2.jpg" />
<img src="http://blog.metrotrends.org/wp-content/uploads/2013/09/childPoverty.jpg" />
<img src="http://www.chinadaily.com.cn/china/images/2010WenUN/attachement/jpg/site1/20100921/0013729ece6b0e01d9691a.jpg" />
</div>
</div>
<div class="clear"></div>
<div class="carousel-buttons-container">
<ul></ul>
</div>
CSS
.clear{clear:both;}
.carousel-container{
width: 600px;
height: 360px;
float: left;
margin: 0;
padding: 0;
position: relative;
overflow: hidden;
}
.right-arrow{
width: 60px;
height: 100%;
background-color: rgba(0,0,0,.5);
position: absolute;
right: 0;
margin: 0;
padding: 0;
z-index: 2;
}
.left-arrow{
width: 60px;
height: 100%;
background-color: rgba(0,0,0,.5);
position: absolute;
left: 0;
margin: 0;
padding: 0;
z-index: 2;
}
.carousel-image-holder{
height:360px;
width: 2400px;
margin: 0;
padding: 0;
position: absolute;
z-index: 1;
}
.carousel-image-holder img{
width: 600px;
float: left;
margin: 0;
padding: 0;
display: inline-block;
}
.carousel-buttons-container{
width: 600px;
text-align: center;
margin: 15px 0 0 0;
padding: 0;
}
.carousel-buttons-container ul{
list-style-type: none;
margin: 0;
padding: 0;
}
.carousel-buttons{
background-color: #dddddd;
height: 18px;
width: 18px;
border-radius: 50%;
display: inline-block;
margin: 0 10px 0 0;
padding: 0;
cursor: pointer;
}
.carousel-buttons:last-of-type{
margin: 0;
}
.active{
background-color: #e67e22;
}
JQUERY
$(".left-arrow").hide();
var numImgs = $('div.carousel-image-holder img').length;
var addId = numImgs;
if(numImgs == 2){
var clicked = 0;
imgCount = numImgs-2;
}else if(numImgs <= 1){
$(".right-arrow").hide();
}else{
var clicked = 1;
imgCount = numImgs-1;
}
if(numImgs > 2){
for (var i=0; i<numImgs; i++){
$("ul").prepend('<li class="carousel-buttons" id="carousel'+addId+'"></li>');
var addId = addId - 1;
}
}else{
}
$(".carousel-buttons").click(function(){
var findIdClicked = $(this).attr("id");
var splitString = findIdClicked.split("carousel")
var findTheNumb = splitString[1];
$(".carousel-buttons").removeClass("active");
$(this).addClass("active");
clicked = parseInt(findTheNumb);
var adjustNumberforSlide = findTheNumb-1;
$(".carousel-image-holder").animate({"left": -(600*adjustNumberforSlide)+"px"});
console.log(clicked);
if(findTheNumb == 1){
$(".left-arrow").hide();
$(".right-arrow").show();
}else if (findTheNumb == numImgs){
$(".right-arrow").hide();
$(".left-arrow").show();
}else{
$(".right-arrow").show();
$(".left-arrow").show();
}
});
$(".carousel-buttons-container").find("li").first().addClass("active");
$(".right-arrow").click(function(){
if (clicked < imgCount){
$(".carousel-image-holder").animate({"left": "-=600px"});
console.log(clicked);
}else{
$(".carousel-image-holder").animate({"left": "-=600px"});
$(".right-arrow").hide();
console.log(clicked);
}
clicked = clicked+1;
$(".left-arrow").show();
$(".carousel-buttons").removeClass("active");
$("#carousel"+clicked).addClass("active");
});
$(".left-arrow").click(function(){
if (clicked > 2){
$(".carousel-image-holder").animate({"left": "+=600px"});
console.log(clicked);
}else{
$(".carousel-image-holder").animate({"left": "+=600px"});
$(".left-arrow").hide();
console.log(clicked);
}
$(".right-arrow").show();
clicked = clicked-1;
$(".carousel-buttons").removeClass("active");
$("#carousel"+clicked).addClass("active");
});
I'll clean up the spacing, just wanted to get this posted
First off, here is the fiddle: http://jsfiddle.net/ribbs2521/Q7C3m/1/
I thought I could run JS on fiddle but it's not working, either way all of my code is on there so I think we should be good.
So, I am trying to create my own custom image viewer which was working great until I tried to implement PREV and NEXT (in the fiddle they are text but they're actually images). I click next and it changes the picture in the viewer but then my overlay div disappears.
The reason I know it actually changes the picture is because if I put an alert at the end of prevImage() and/or nextImage() I see the changed picture, but once I click OK it all disappears.
I don't know what is going on. I am not sure if it's my JS or CSS causing the issue, I am fairly new to JS, CSS and HTML.
Can anyone tell me why my div disappears after this function is performed?
Here is the JS:
var images = Array();
var cursor = 0;
function showHide(obj) {
alert("Working");
var overlay = document.getElementById("ImgOverlay");
if (obj instanceof HTMLImageElement) {
// Get list of images in gallery
var gallery = document.getElementById("gallery");
images = gallery.getElementsByTagName("img");
cursor = -1;
while (images[++cursor].src != obj.src) {}
// Show the image
putImageInViewer(obj);
overlay.style.display = "block";
} else if (overlay.style.display !== "none" && overlay.style.display !== "") { // If it's the div that you clicked...
hideElement(overlay);
}
}
function hideElement(element) {
element.style.display = "none";
}
function putImageInViewer(obj) {
var img = new Image();
img.src = obj.src;
var size = 600;
var h = img.height;
var w = img.width;
// We want a max size of 600 but don't want to blow images up (bad graphics)
// Images should be their actual size but limited to 600px MAX
if (h <= 600 && w <= 600) {
if (h > w) {
size = h;
} else {
size = w;
}
}
if (h > w) {
document.getElementById("overlay-img").innerHTML = "<img src=\"" + img.src + "\" height=\"" + size + "\">";
} else {
document.getElementById("overlay-img").innerHTML = "<img src=\"" + img.src + "\" width=\"" + size + "\">";
}
}
function nextImage() {
// Check if we need to loop around
if (cursor < images.length) {
cursor++;
} else {
cursor = 0;
}
putImageInViewer(images[cursor]);
}
function prevImage() {
// Check if we need to loop around
if (cursor > 0) {
cursor--;
} else {
cursor = images.length;
}
putImageInViewer(images[cursor]);
}
Here is the CSS:
#wrap {
margin: 0 auto;
}
#wrap li {
float:left;
position:relative;
display:inline-block;
width:240px;
height:240px;
margin:10px;
padding:10px;
background:#fff;
box-shadow:0 0 5px rgba(0, 0, 0, .35);
overflow: hidden;
}
#wrap li div {
position:absolute;
height:0;
width:220px;
background:rgba(0, 0, 0, .45);
overflow:hidden;
bottom:10px;
left:10px;
padding: 0 10px;
line-height:50px;
color:#fff;
transition:height 1s;
}
#wrap li:hover div {
height:50px;
}
#wrap li img {
width: 240px;
height: 240px;
margin: 0px 0 0 0px;
cursor: pointer;
}
#ImgOverlay {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background-color: rgb(0, 0, 0);
/*fallback*/
background-color: rgba(0, 0, 0, 0.6);
/*background-image:none;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;*/
display: none;
}
#imgnav {
position: fixed;
top: 38%;
left: 50%;
margin: -15px 0 0 -363px;
width: 730px;
height: 60px;
}
#overlay-img {
position: fixed;
top: 50%;
left: 50%;
margin: -300px 0 0 -300px;
width: 600px;
height: 600px;
}
#overlay-img img {
border: 2px solid white;
display: block;
margin: auto;
}
And finally, the HTML:
<div id="wrap">
<h1>An Image Gallery</h1>
<ul id="gallery">
<li>
<img src="w" onclick="showHide(this);">
<div>Image 1</div>
</li>
<li>
<img src="w" onclick="showHide(this);">
<div>Image 2</div>
</li>
</ul>
<div id="clear"></div>
</div>
<!-- For Image Viewer -->
<div id="ImgOverlay" onclick="showHide(this);">
<div id="imgnav"> <span style="color: white; cursor: pointer; float: left" height="60px" width="60px" onclick="prevImage();">PREV</span>
<div id="overlay-img">
<!-- Image will go here -->
</div> <span style="color: white; cursor: pointer; float: left" height="60px" width="60px" onclick="prevImage();">NEXT</span>
</div>
</div>
<!-- End Image Viewer -->
You are probably running into JavaScript event propagation. In a nutshell, events that fire on DOM elements (such as the "click" event on your "PREV" and "NEXT" buttons), bubble up the DOM, firing again on each of the original element's parents. In your case, this means that when you click your "NEXT" button, it fires prevImage() and then when the event bubbles up to ImgOverlay, it fires showHide(this).
You need to modify your event handlers to tell the browser not to propagate the event. Change your button markup to something like the following:
<span id="nextButton" style="color: white; cursor: pointer; float: left" height="60px" width="60px">NEXT</span>
Then use the following to handle the click event:
var nextButton = document.getElementById('nextButton');
nextButton.onclick = function (ev) {
nextImage();
if (!ev) {
// Old versions of Internet Explorer do not pass the event to handlers.
ev = window.event;
}
ev.cancelBubble = true;
if (ev.stopPropagation) {
// W3C standard, works in Chrome, Firefox, Safari, etc.
ev.stopPropagation();
}
};
I'm attempting to make the navigation bar stick to the top, when the user scrolls down to the nav bar and then unstick when the user scrolls back up past the navbar. I understand that this can only be implemented via JavaScript. I'm a beginner to JavaScript, so the easier the better. The JSFIDDLE is here.
The HTML is as follows:
<section class="main">
<div id="wrap">
<div id="featured">
<div class="wrap">
<div class="textwidget">
<div class="cup"><img src="#""></div>
<div id="header"></div></div></div></div></div></div></div>
<div class="whiteboard">
<h1>HELLO GUYS</h1> </div>
</div>
<div class="bg1">
<h2> WE ARE AN EVENTS MANAGEMENT COMPANY BASED IN LONDON. </h2></div>
The CSS is as follows:
.main{text-align:center;}
h1{
-webkit-font-smoothing: antialiased;
display:inline-block;
font: 800 1.313em "proxima-nova",sans-serif;
padding: 10px 10px;
margin: 20px 20px;
letter-spacing: 8px;
text-transform: uppercase;
font-size:3.125em;
text-align: center;
max-width: 606px;
line-height: 1.45em;
position: scroll;
background-color:#e94f78;
text-decoration: none;
color:yellow;
background-image:url;
}
h1 a{
text-decoration: none;
color:yellow;
padding-left: 0.15em;
}
h2{
-webkit-font-smoothing: antialiased;
display:inline-block;
font: 800 1.313em "proxima-nova",sans-serif;
letter-spacing: 8px;
margin-top: 100px;
text-transform: uppercase;
font-size:3.125em;
text-align: center;
line-height: 1.45em;
position: scroll;
text-decoration: none;
color:white;
z-index: -9999;
}
h2 a{
text-decoration: none;
color:white;
padding-left: 0.15em;
}
h5{
position: absolute;
font-family:sans-serif;
font-weight:bold;
font-size:40px;
text-align: center;
float: right;
background-color:#fff;
margin-top: -80px;
margin-left: 280px;
}
h5 a{
text-decoration: none;
color:red;
}
h5 a:hover{
color:yellow;
}
#text1{
-webkit-font-smoothing: antialiased;
display:inline-block;
font: 800 1.313em "proxima-nova",sans-serif;
margin: 20px 20px;
letter-spacing: 8px;
text-transform: uppercase;
font-size:3.125em;
text-align: center;
max-width: 606px;
line-height: 1.45em;
position: scroll;
background-color:#E94F78;
}
#text1 a{
color:yellow;
text-decoration: none;
padding-left: 0.15em;
}
#text1 a:hover{
text-decoration: none;
cursor:pointer;
}
.whiteboard{
background-image:url(http://krystalrae.com/img/krystalrae-2012-fall-print-leopard-sketch.jpg);
background-position: center;
padding: ;
background-color: #fff;
z-index: 1000;
}
.bg{
height:2000px;
background-color:#ff0;
background-image:url(http://alwayscreative.net/images/stars-last.jpg);
position:relative;
z-index: -9999;
}
.bg1{
background-image:url(http://alwayscreative.net/images/stars-last.jpg);
z-index: -9999;
height:1000px;
}
/* Header */
#wrap {
margin: 0 auto;
padding: 0;
width: 100%;
}
#featured {
background: #E94F78 url(http://www.creativityfluid.com/wp-content/themes/creativityfluid/images/img-bubbles-red.png) no-repeat top;
background-size: 385px 465px;
color: #fff;
height: 535px;
overflow: hidden;
position: relative;
z-index: -2;
}
#featured .wrap {
overflow: hidden;
clear: both;
padding: 70px 0 30px;
position: fixed;
z-index: -1;
width: 100%;
}
#featured .wrap .widget {
width: 80%;
max-width: 1040px;
margin: 0 auto;
}
#featured h1,
#featured h3,
#featured p {
color: yellow;
text-shadow: none;
}
#featured h4{
color:white;
text-shadow:none;
}
#featured h4 {
margin: 0 0 30px;
}
#featured h3 {
font-family: 'proxima-nova-sc-osf', arial, serif;
font-weight: 600;
letter-spacing: 3px;
}
#featured h1 {
margin: 0;
}
.textwidget{
padding: 0;
}
.cup{
margin-top:210px;
z-index: 999999;
}
.container{font-size:14px; margin:0 auto; width:960px}
.test_content{margin:10px 0;}
.scroller_anchor{height:0px; margin:0; padding:0;background-image:url()}
.scroller{background:#FFF;
background-image:url(http://krystalrae.com/img/krystalrae-2012-fall-print-leopard-sketch.jpg);
margin:0 0 10px; z-index:100; height:50px; font-size:18px; font-weight:bold; text-align:center; width:960px;}
You can do that with some easy jQuery:
http://jsfiddle.net/jpXjH/6/
var elementPosition = $('#navigation').offset();
$(window).scroll(function(){
if($(window).scrollTop() > elementPosition.top){
$('#navigation').css('position','fixed').css('top','0');
} else {
$('#navigation').css('position','static');
}
});
I wouldn't bother with jQuery or LESS. A javascript framework is overkill in my opinion.
window.addEventListener('scroll', function (evt) {
// This value is your scroll distance from the top
var distance_from_top = document.body.scrollTop;
// The user has scrolled to the tippy top of the page. Set appropriate style.
if (distance_from_top === 0) {
}
// The user has scrolled down the page.
if(distance_from_top > 0) {
}
});
There are some problems implementing this which the original accepted answer does not answer:
The onscroll event of the window is firing very often. This
implies that you either have to use a very performant listener, or
you have to delay the listener somehow. jQuery Creator John Resig
states here how a
delayed mechanism can be implemented, and the reasons why you should
do it. In my opinion, given todays browsers and environments, a
performant listener will do as well. Here is an implementation of the pattern suggested by John Resig
The way position:fixed works in css, if you scroll down the page and move an element from position:static to position: fixed, the page will "jump" a little because the document "looses" the height of the element. You can get rid of that by adding the height to the scrollTop and replace the lost height in the document body with another object. You can also use that object to determine if the sticky item has already been moved to position: fixed and reduce the calls to the code reverting position: fixed to the original state: Look at the fiddle here
Now, the only expensive thing in terms of performance the handler is really doing is calling scrollTop on every call. Since the interval bound handler has also its drawbacks, I'll go as far as to argue here that you can reattach the event listener to the original scroll Event to make it feel snappier without many worries. You'll have to profile it though, on every browser you target / support. See it working here
Here's the code:
JS
/* Initialize sticky outside the event listener as a cached selector.
* Also, initialize any needed variables outside the listener for
* performance reasons - no variable instantiation is happening inside the listener.
*/
var sticky = $('#sticky'),
stickyClone,
stickyTop = sticky.offset().top,
scrollTop,
scrolled = false,
$window = $(window);
/* Bind the scroll Event */
$window.on('scroll', function (e) {
scrollTop = $window.scrollTop();
if (scrollTop >= stickyTop && !stickyClone) {
/* Attach a clone to replace the "missing" body height */
stickyClone = sticky.clone().prop('id', sticky.prop('id') + '-clone')
stickyClone = stickyClone.insertBefore(sticky);
sticky.addClass('fixed');
} else if (scrollTop < stickyTop && stickyClone) {
/* Since sticky is in the viewport again, we can remove the clone and the class */
stickyClone.remove();
stickyClone = null;
sticky.removeClass('fixed');
}
});
CSS
body {
margin: 0
}
.sticky {
padding: 1em;
background: black;
color: white;
width: 100%
}
.sticky.fixed {
position: fixed;
top: 0;
left: 0;
}
.content {
padding: 1em
}
HTML
<div class="container">
<div id="page-above" class="content">
<h2>Some Content above sticky</h2>
...some long text...
</div>
<div id="sticky" class="sticky">This is sticky</div>
<div id="page-content" class="content">
<h2>Some Random Page Content</h2>...some really long text...
</div>
</div>
Here you go, no frameworks, short and simple:
var el = document.getElementById('elId');
var elTop = el.getBoundingClientRect().top - document.body.getBoundingClientRect().top;
window.addEventListener('scroll', function(){
if (document.documentElement.scrollTop > elTop){
el.style.position = 'fixed';
el.style.top = '0px';
}
else
{
el.style.position = 'static';
el.style.top = 'auto';
}
});
You want to use jQuery WayPoints. It is a very simple plugin and acheives exactly what you have described.
Most straightforward implementation
$('.thing').waypoint(function(direction) {
alert('Top of thing hit top of viewport.');
});
You will need to set some custom CSS to set exactly where it does become stuck, this is normal though for most ways to do it.
This page will show you all the examples and info that you need.
For future reference a example of it stopping and starting is this website. It is a "in the wild" example.
You can go to LESS CSS website http://lesscss.org/
Their dockable menu is light and performs well. The only caveat is that the effect takes place after the scroll is complete. Just do a view source to see the js.
You can do this with css too.
just use position:fixed;
for what you want to be fixed when you scroll down.
you can have some examples here:
http://davidwalsh.name/demo/css-fixed-position.php
http://demo.tutorialzine.com/2010/06/microtut-how-css-position-works/demo.html
window.addEventListener("scroll", function(evt) {
var pos_top = document.body.scrollTop;
if(pos_top == 0){
$('#divID').css('position','fixed');
}
else if(pos_top > 0){
$('#divId').css('position','static');
}
});
Plain Javascript Solution (DEMO) :
<br/><br/><br/><br/><br/><br/><br/>
<div>
<div id="myyy_bar" style="background:red;"> Here is window </div>
</div>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<script type="text/javascript">
var myyElement = document.getElementById("myyy_bar");
var EnableConsoleLOGS = true; //to check the results in Browser's Inspector(Console), whenever you are scrolling
// ==============================================
window.addEventListener('scroll', function (evt) {
var Positionsss = GetTopLeft ();
if (EnableConsoleLOGS) { console.log(Positionsss); }
if (Positionsss.toppp > 70) { myyElement.style.position="relative"; myyElement.style.top = "0px"; myyElement.style.right = "auto"; }
else { myyElement.style.position="fixed"; myyElement.style.top = "100px"; myyElement.style.right = "0px"; }
});
function GetOffset (object, offset) {
if (!object) return;
offset.x += object.offsetLeft; offset.y += object.offsetTop;
GetOffset (object.offsetParent, offset);
}
function GetScrolled (object, scrolled) {
if (!object) return;
scrolled.x += object.scrollLeft; scrolled.y += object.scrollTop;
if (object.tagName.toLowerCase () != "html") { GetScrolled (object.parentNode, scrolled); }
}
function GetTopLeft () {
var offset = {x : 0, y : 0}; GetOffset (myyElement.parentNode, offset);
var scrolled = {x : 0, y : 0}; GetScrolled (myyElement.parentNode.parentNode, scrolled);
var posX = offset.x - scrolled.x; var posY = offset.y - scrolled.y;
return {lefttt: posX , toppp: posY };
}
// ==============================================
</script>
The solution that worked for me lately is:
.sticky {
position: fixed;
top: 0;
width: 100%;
}
var header = document.getElementById("filters-tab");
var sticky = header.offsetTop;
if (window.pageYOffset > sticky) {
header.classList.add("fixed");
} else {
header.classList.remove("fixed");
}
Javascript is no longer required for this.
Do this using the CSS position:sticky property
https://css-tricks.com/position-sticky-2/