Set divs opacity related to scroll position - javascript

I'm trying to set the opacity of a series of divs based on their individual proximity to scrollbar position.
This is what I have so far - http://jsfiddle.net/jGeYg/1/
I've managed to set the opacity to 0 when you are at the top of the window and it raise to 1 as you get to the top of div.
What I'm trying to acheive is for it not to start raising in opacity until you are 50px above the div and hit full opacity when you are at the top of the div. Essentially it's range where opacity changes is
$('div').position().top - 50 -> $('div').position().top //psuedo code
I don't want to use a plugin. I'm having trouble with the math rather than the code.

http://jsfiddle.net/b9ZCk/3/
I've added some debug text to show the position and opacity.

I am not sure if this is the desired effect that you want.. but try and let me know,
$(window).scroll(function() {
var st = $(this).scrollTop();
$('.block').each(function(index) {
if (($(this).offset().top-st) < 50) {
$(this).css({
'opacity': (0 + (st / $(this).offset().top))
});
} else {
$(this).css({'opacity': 0.1});
}
})
});
DEMO: http://jsfiddle.net/skram/jGeYg/5/

Related

Stop element from being fixed once scrolled past value

I have a fixed .widget element that remains visible at all times. Currently however, it scrolls over the footer area. My goal is to stop the widget before it hits the footer.
CSS
.widget {
position:fixed;
height:450px;
width:300px;
}
footer {
height:450px;
width:100%;
}
My route I'm taking is currently:
jQuery
var $bodyheight = $('body').height();
var $footerheight = $('footer').height();
var $widgetheight = $('.game_widget').height();
var $pageheight = $bodyheight - $footerheight - $widgetheight;
$(window).on('scroll', function() {
console.log($(this).scrollTop())
});
My next step would be to loop through to see if scrollTop > $pageheight then update some CSS.
Is this the best way of going about this? Is there a cleaner/simpler way to achieve the same result?
I have managed to solve this quite simply. Inside the scroll function I set 2 variables, one for the position of the fixed element, the other for the position of the footer. These return the exact value from how far the top of the element is from the top of the page. For the fixed element I need to know the distance to the bottom of this element so I also include the height.
var $fixedpos = $(".game_widget").offset().top + $('.game_widget').height();
var $footerpos = $("footer").offset().top - 25; // 25 accounts for margin
Using a simple if/else the CSS is updated to display none/initial depending on whether $fixedpos > $footerpos (i.e. the fixed element is overlapping the footer).
if ($fixedpos > $footerpos) {
$('.game_widget').css('display','none');
} else {
$('.game_widget').css('display','initial');
}
This works, however there is a 'flicking' effect as the fixed element overlaps the footer. This is due to the function executing extremely rapidly. The solution to the flicker is to use this simple 'throttling' plugin that adds a short delay (of your choice) between each execution of a function - http://benalman.com/projects/jquery-throttle-debounce-plugin/
You then just need to bind the on scroll function to the throttle:
function scrolling() {
console.log($(".game_widget").offset().top + $('.game_widget').height());
console.log($("footer").offset().top - 25);
var $fixedpos = $(".game_widget").offset().top + $('.game_widget').height();
var $footerpos = $("footer").offset().top - 25;
if ($fixedpos > $footerpos) {
$('.game_widget').css('display', 'none');
} else {
$('.game_widget').css('display', 'initial');
}
};
$(window).on('scroll', $.throttle(250, scrolling)); // 250ms between executing the function
});
This 250ms delay stops the function from executing so rapidly that the flickering effect occurs.
Hope this helps others trying to solve this problem.

Hide a div at specfic height while using slidetoggle()

I have three divs and i am trying to show/hide div2 when we click on any div. So far i have succeeded in it but now i want to implement some animation while show.hide the div.
I tried a lot and read many solution but due to i am new to jQuery i cant do it. Here is my code that i tried before animation
http://jsfiddle.net/9Lw6T/119/
$(".more , .expander,.headingopen").click(function() {
var expanderDiv = $(this).parents(".content_item").find(".textContent");
if ($(expanderDiv).length > 0 && $(expanderDiv).hasClass("expander") ) {
$(expanderDiv).removeClass("expander");
var MoreDiv = $(this).parents(".content_item").find(".more");
$(MoreDiv).html("Mindre");
}
else {
console.log("addclass");
$(expanderDiv).addClass("expander new");
var MoreDiv = $(this).parents(".content_item").find(".more");
$(MoreDiv).html("More");
}
});
jQuery(document).ready(function() {
jQuery(".more , .expander,.headingopen").click(function() {
jQuery('.expander').slideToggle("slow");
});
});
After Animation or slidetoggle
http://jsfiddle.net/9Lw6T/123/
Is there any way to animate the divs and stop at certain height while slideup as before animation i have done it in my first try without animate. Slidedown needs auto hide and its working with this code.
Thanks
There is an issue when using jQuery animate going to auto so you have to do a little work around (see: JavaScript jQuery Animate to Auto Height)
// get the current height
var curHeight = $textArea.height();
// set set the css to auto height and get how tall it is
var autoHeight = $textArea.css('height', 'auto').height();
// set the css back to the original height, then animate to the new height
$textArea.height(curHeight).animate({height: autoHeight}, 1000);
Here it is all together
http://jsfiddle.net/9Lw6T/127/

Randomize image position with JQuery and HTML

I have this :
<div id="randomp" style="position:absolute;top:3px;left:3px;width:165px;height:29px;background:url(/logo2.png) no-repeat;background-size: 165px;"></div>
I want that the propierty "top" and "left" change every time you enter into the page. I mean that some times it appear on the right top corner, right bottom corner, left top corner and left bottom corner..
Here it is what i have tryied:
http://redzer.com.mx/tabla.html
I would probably start with the div styled as position:fixed and with display:none:
<div id="randomp" style="display:none;position:fixed;width:165px;height:29px;background:url(/logo2.png) no-repeat;background-size: 165px;"></div>
Then use jQuery to determine the position CSS to set and turn on visibility
$(document).ready(function() {
// get jQuery object for the div
var $randomp = $('#randomp');
// determine whether to show top or bottom, left or right
var top = Math.round(Math.random()); // generate 0 or 1 value
if (top === 1) {
$randomp.css('top', '3px');
} else {
$randomp.css('bottom', '3px');
}
var left = Math.round(Math.random());
if (left === 1) {
$randomp.css('left', '3px');
} else {
$randomp.css('right', '3px');
}
// show the div
$randomp.show();
});
Of course, you could also use server-side code to do this, but since you asked specifically about javascript/jquery in your tags, I suggested this solution.
I think i got exactly what you need.
EXAMPLE
With javascript i am generating random numbers for the top and left positioning of your image every time you visit the page.
Right now i set them up to get a random number between 0 and 100 but you can change that to whatever you want.
var random1 = Math.ceil(Math.random() * 100);
var random2 = Math.ceil(Math.random() * 100);
$(document).ready(function () {
$('#randomp').css('top', random1);
$('#randomp').css('left', random2);
});

How to drag a DIV so its width and height are negative values?

I'm a bit stumped here. I am developing a feedback utility that will allow the user to "draw" boxes on a web page to highlight problem areas. Right now I have an overlay DIV that fills the screen and jQuery allows you to draw red outlined DIVs by clicking and dragging.
Here is the JS:
{
var $feedbackOverlay = jQuery('#feedbackOverlay');
var $original = { top: 0, left:0 };
$feedbackOverlay.bind('mousedown', function (e)
{
jQuery('<div id="currentHighlight"></div>')
.css('width', '1px')
.css('height', '1px')
.css('border', 'solid 3px #ff0000')
.css('border-radius', '5px')
.css('position', 'absolute')
.css('left', e.pageX)
.css('top', e.pageY)
.css('z-index', '8000001')
.appendTo('body');
$original = { top: e.pageY, left: e.pageX };
});
$feedbackOverlay.bind('mousemove', function (e)
{
var $currentHighlight = jQuery('#currentHighlight');
if ($currentHighlight.length > 0)
{
var $pos = { top: e.pageY, left: e.pageX };
if($pos.top < $original.top) $currentHighlight.css('top', $pos.top);
if ($pos.left < $original.left) $currentHighlight.css('left', $pos.left);
$currentHighlight.height(Math.abs($pos.top - $original.top));
$currentHighlight.width(Math.abs($pos.left - $original.left));
}
});
$feedbackOverlay.bind('mouseup', function (e)
{
var $currentHighlight = jQuery('#currentHighlight');
$currentHighlight.removeAttr('id');
});
var $feedbackInstructions = jQuery('#feedbackInstructions');
$feedbackInstructions.fadeIn(1000, function ()
{
setTimeout(function ()
{
$feedbackInstructions.fadeOut(1000);
}, 3000);
});
$feedbackOverlay.height(jQuery(document).height());
});
Here is a jsFiddle for the above:
http://jsfiddle.net/Chevex/RSYTq/
The problem is that I can't drag the boxes up or left. The first click puts the top left corner where the mouse clicked. After that subsequent dragging will change the width of the box. Letting go of the mouse completes the box and you may then start drawing another one. If you try to drag the DIV left or up while drawing it's width will remain at 0 but won't go negative.
Here you can find working solution: http://jsfiddle.net/RSYTq/34/
Something like this will get you closer to what you want: http://jsfiddle.net/RSYTq/18/
Doesn't quite handle move up and to the left and then switching to moving down and to the right quite right yet but it gives you the idea.
There's no such thing a a negative width - these are not coorindinates. You need to reposition and recalculate the corner positions relative to the corner that's not being moved.
Sounds like you need to check if the click origin (x,y) is > than the current mouse position, and then swap which one you use for the CSS top-left.
You would need to track the original start point somewhere (variables, data attributes on #currentHighlight, wherever you want), and check for width or height < 0. When so, set the #currentHighlight left/top CSS to be offset by original + (e.pageX - $currentHighlight.position().left) (for example). Then set the #currentHighlight width/height to the same difference (but positive: (e.pageX - $currentHighlight.position().left) * -1).

Fading Element on Scroll

I'm curious how I can create a DIV (or anything really) that I can fade (or change opacity of) when a user scrolls down the page. This DIV would sit at the top of the page, but only be clearly visible when at the very top of the page.
Additionally, it would be ideal if I I could have this element fade back in onmouseover, regardless of the current scrolled position on the page.
jQuery would allow for a succinct solution, whilst hiding most browser discrepancies. Here's a quick mock-up to get you started:
<script type="text/javascript">
//when the DOM has loaded
$(document).ready(function() {
//attach some code to the scroll event of the window object
//or whatever element(s) see http://docs.jquery.com/Selectors
$(window).scroll(function () {
var height = $('body').height();
var scrollTop = $('body').scrollTop();
var opacity = 1;
// do some math here, by placing some condition or formula
if(scrollTop > 400) {
opacity = 0.5;
}
//set the opacity of div id="someDivId"
$('#someDivId').css('opacity', opacity);
});
});
</script>
See also:
jQuery
Selectors
CSS
Events/Scroll
CSS/ScrollTop
CSS/ScrollLeft
I thought I would give it a go using the actual value of scrollTop to dictate the opacity level, thus getting a smooth fade. I also added the hover state for the second part. Thanks to David for refining the maths for me.
//reduce the opacity of the banner if the page is scrolled.
$(window).scroll(function () {
var height = $("body").height();
var scrollTop = $("body").scrollTop();
var opacity = 1;
if(scrollTop < 41)
{opacity = 1-Math.floor(scrollTop)/100;}
else
{opacity = 0.6;}
$("#header").css("opacity", opacity);
$("#header").hover(function(){
$(this).css("opacity", 1);
},function(){
$(this).css("opacity", 0.6);
});
});
Use scroll event, and analyse value of document.documentElement.scrollTop to set appropriated opacity.
http://www.quirksmode.org/dom/events/scroll.html

Categories