My goal is to save the scroll position inside a div ,so that after reload it will load in the same position.
In my project im using this plugin to scroll to element inside a div by its title. the current way i'm using this plugin is this:
$("#wrapper").scrollTo($(".active>.placementWrapper>.placementName[title='" + placementName + "']"));
var scrollToPos = placementName;
localStorage.setItem("scrollToPos", scrollToPos);
but as you can see, i use element's title to get the position i need to scroll to, so when im scrolling with the mouse for example, the position won't update.
this is the code of the plugin:
$.fn.scrollTo = function( target, options, callback ){
if(typeof options == 'function' && arguments.length == 2){ callback = options; options = target; }
var settings = $.extend({
scrollTarget : target,
offsetTop : 50,
duration : 500,
easing : 'swing'
}, options);
return this.each(function(){
var scrollPane = $(this);
var scrollTarget = (typeof settings.scrollTarget == "number") ? settings.scrollTarget : $(settings.scrollTarget);
var scrollY = (typeof scrollTarget == "number") ? scrollTarget : scrollTarget.offset().top + scrollPane.scrollTop() - parseInt(settings.offsetTop);
scrollPane.animate({scrollTop : scrollY }, parseInt(settings.duration), settings.easing, function(){
if (typeof callback == 'function') { callback.call(this); }
});
});
}
bottom line, any idea how can i save the last position inside the #wrapper ? thx
Try using just this to store.:
<div id="test" style="height:460px;"></div>
<script>
localStorage.hval=(document).getElementById("test").style.height;
</script>
To get the value again,
localStorage.getItem("hval");
You can replace hval with pretty much anything you want.To check the LocalStorage, go to the Dev tools>Resources>Local Storage
Related
How to be sure if parent element has css position property setted up ?
if(!$('#element').parent().css('position')){
//here I need to be sure to avoid no rewrite the old position if position is already setted up
//absolute fixed etc....
$('#element').parent().css('position','relative')
}
Some like this work on cross browsers ?
Please follow the below method :
function elementOrParentIsFixed(element) {
var $element = $(element);
var $checkElements = $element.add($element.parents());
var isFixed = false;
$checkElements.each(function(){
if ($(this).css("position") === "relative") {
isFixed = true;
return false;
}
});
return
}
So based on #Danish suggestion (copy-pasted from : Detect whether an element has position:fixed (possibly by parent element) via jQuery )
I write this:
function parentHasPosition(element){
var parent = element.parent();
if(
parent.css('position') === 'static' ||
parent.css('position') === 'absolute' ||
parent.css('position') === 'fixed' ||
parent.css('position') === 'sticky'
){
return true;
}
return false;
}
EDIT (12/26/2012)
I found the following code which does exactly what I want, except now when a page's URL has a trailing slash (e.g. example.com/page/), the page doesn't scroll. Works fine if the page's URL ends with '.php' or '.html', etc. Any thoughts on how to get the following script to work with the trailing slash in a URL?
jQuery('a[href*=#]').bind('click', function(e) {
// Get the target
var target = jQuery(this).attr("href");
// prevent the "normal" behaviour which would be a "hard" jump
e.preventDefault();
// perform animated scrolling by getting top-position of target-
// element and set it as scroll target
jQuery('html, body').stop().animate({
scrollTop: jQuery(target).offset().top
}, 500, function() {
location.hash = target; //attach the hash (#jumptarget) to the pageurl
});
return false;
});
I've been using a script successfully for the last couple of years, but have recently run into some issues with it. Basically what the script does is scroll the page to a specific point. This happens with link anchors. For example, if one link is:
anchor link
The page will smoothly scroll to that anchor on the page:
<a name="anchor"></a>
Or:
<a id="anchor"></a>
The issue that occurs arises when some other JS is being used in the page which requires a link to be formatted as such:
other link
When this "other link" is clicked, the page will smoothly scroll, BUT to the top or bottom of the page where there is NO anchor.
What should happen when this "other link" is clicked? The other JS action should occur (which it does), but the smooth page scrolling script should not occur.
Here's a working example from where I got this script:
http://www.dezinerfolio.com/wp-content/uploads/smoothscrolldemo/df_smooth_scroll.html
Here's the JS in full:
Scroller = {
// control the speed of the scroller.
// dont change it here directly, please use Scroller.speed=50;
speed: 10,
// returns the Y position of the div
gy: function (d) {
gy = d.offsetTop
if (d.offsetParent) while (d = d.offsetParent) gy += d.offsetTop
return gy
},
// returns the current scroll position
scrollTop: function (){
body = document.body
d = document.documentElement
if (body && body.scrollTop) return body.scrollTop
if (d && d.scrollTop) return d.scrollTop
if (window.pageYOffset) return window.pageYOffset
return 0
},
// attach an event for an element
// (element, type, function)
add: function(event, body, d) {
if (event.addEventListener) return event.addEventListener(body, d,false)
if (event.attachEvent) return event.attachEvent('on'+body, d)
},
// kill an event of an element
end: function(e){
if (window.event) {
window.event.cancelBubble = true
window.event.returnValue = false
return;
}
if (e.preventDefault && e.stopPropagation) {
e.preventDefault()
e.stopPropagation()
}
},
// move the scroll bar to the particular div.
scroll: function(d){
i = window.innerHeight || document.documentElement.clientHeight;
h = document.body.scrollHeight;
a = Scroller.scrollTop()
if (d>a)
if(h-d>i)
a += Math.ceil((d-a)/Scroller.speed)
else
a += Math.ceil((d-a-(h-d))/Scroller.speed)
else
a = a + (d-a)/Scroller.speed;
window.scrollTo(0,a)
if (a==d || Scroller.offsetTop==a)
clearInterval(Scroller.interval)
Scroller.offsetTop = a
},
// initializer that adds the renderer to the onload function of the window
init: function(){
Scroller.add(window,'load', Scroller.render)
},
// this method extracts all the anchors and validates then as # and attaches the events.
render: function(){
a = document.getElementsByTagName('a');
Scroller.end(this);
window.onscroll
for (i=0;i<a.length;i++) {
l = a[i];
if (l.href && l.href.indexOf('#') != -1 && ((l.pathname==location.pathname) || ('/'+l.pathname==location.pathname)) ){
Scroller.add(l,'click',Scroller.end)
l.onclick = function(){
Scroller.end(this);
l = this.hash.substr(1);
a = document.getElementsByTagName('a');
for (i=0;i<a.length;i++) {
if (a[i].name == l){
clearInterval(Scroller.interval);
Scroller.interval = setInterval('Scroller.scroll('+Scroller.gy(a[i])+')',10);
}
}
}
}
}
}
}
// invoke the initializer of the scroller
Scroller.init();
I would think that there is a way to write the script so that if the href is equal to just the hash mark # without any text after the hash, that the scroller wouldn't be triggered.
Does anyone have any better ideas?
Thanks in advance!
I can't help you with your jQuery function, but there are two simple solutions to your original script. The first is a small modification to tell the script to ignore the special case where an anchor's URL is only the hash tag.
In the render function, change the line:
if (l.href
&& l.href.indexOf('#') != -1
&& (l.pathname == location.pathname
|| '/' + l.pathname == location.pathname)
) {
To:
if (l.href
&& l.href != '#' // <<< Added this conditional >>>
&& l.href.indexOf('#') != -1
&& (l.pathname == location.pathname
|| '/' + l.pathname == location.pathname)
){
This will tell the script to ignore the special case, but won't prevent the browser from reacting normally to the link, so the browser may still jump to the top of the page. The special case you've mentioned is almost always used in javascript constructions to provide an anchor tag with an href attribute, because some older browsers would ignore the tag without one. The '#' was used as the URL to prevent the link from leaving the page.
Instead of the '#', you could use an empty javascript call in your link, like so:
other link
This will avoid your issues with the scrollers completely.
Thanks again, Jarred, for your help! I did come across a script that does just what I want. Here's the better script I found:
jQuery('a[href*=#]').bind('click', function(e) {
e.preventDefault(); //prevent the "normal" behaviour which would be a "hard" jump
var target = jQuery(this).attr("href"); //Get the target
// perform animated scrolling by getting top-position of target-element and set it as scroll target
jQuery('html, body').stop().animate({ scrollTop: jQuery(target).offset().top }, 1000, function() {
location.hash = target; //attach the hash (#jumptarget) to the pageurl
});
return false;
});
I'm trying to handle mouseover / mouseout animations and a statement I have is not evaluating to true when you mouseover an element that you previously moused over. I'm trying to prevent a double rollover animation from happening. Here's my code:
var $chosenThumb = null;
var $lastThumb = null;
$('.thumb_img').mouseover(function(){
if ($chosenThumb != null){
$lastThumb = $chosenThumb;
$lastThumbContainer = $chosenThumb.parent();
$lastThumbOverlay = $lastThumbContainer.children('.thumb_overlay');
}
$chosenThumb = $(this);
console.log($lastThumb + "|" + $chosenThumb + "|" + ($lastThumb == $chosenThumb));
$chosenThumbContainer = $(this).parent();
$chosenThumbOverlay = $chosenThumbContainer.children('.thumb_overlay');
if ($lastThumb != null && $lastThumb != $chosenThumb){
$lastThumbOverlay.animate({ 'height' : '0px'}, 200);
$lastThumbContainer.children('.thumb_plus').animate({'height' :'0px', 'width' : '0px' },200);
}
if ($lastThumb != $chosenThumb) {
$chosenThumbOverlay.animate({ 'height' : '30px'}, 200);
$chosenThumbContainer.children('.thumb_plus').animate({'height' :'31px', 'width' : '31px' },200);
}
});
So the first time you mouse over a thumbnail, lastThumb will be null and chosenThumb will be the thumb you rolled over. Then the next time you mouse over that thumb, lastThumb should be equal to chosenThumb, but the log statement does not evaluate as true. Why?
Even with the same selector, every jQuery object is a new instance of jQuery. To compare elements, you have to compare the actual DOM element:
//$lastThumb[0] returns the first DOM element from the jQuery selector
$lastThumb[0] == $chosenThumb[0]
Generally it's unadvisable to extend DOM elements because of memory leaks but I might suggest you do it in this case if you don't have a large number of nodes.
This will prevent a mouseover event from firing if it has fired once:
$( "myselector" ).mouseover( function( )
{
if ( this.moused )
{
return;
}
else
{
this.moused = true;
}
// Do things here.
} );
May be you have two span or div with the same ids in your HTML
I want #result to being scaled to #sidebar height if set. If not, leaving #result at its original height.
My code:
window.onload = setDiv;
function setDiv() {
var e = document.getElementById('sidebar'); // Get the sidebar infos
var eh = e.offsetHeight // div height
if ( typeof(eh) == "undefined" || typeof(eh) == null) { // if sidebar isnt in the page
alert(eh);
return true;
} else {
var eh = e.offsetHeight // div height
var d = document.getElementById('result') // Get the result div height
var dh = d.offsetHeight // div height
d.style.height = eh + 65 + 'px'; // Set result div height to sidebar height
alert(d);
document.write(dh);
return false;
}
}
I don't think HTML/CSS is needed.
Thank you.
This line seems wrong:
if ( typeof(eh) == "undefined" || "null") { // if sidebar isnt in the page
try this:
if ( typeof(eh) == "undefined" || typeof(eh) == null) { // if sidebar isnt in the page
Also, I would add in a try catch block. If there is a throw you won't even know your code did not execute.
This causes an error because e does not exist (yet):
var e = document.getElementById('sidebar'); // <<< This is what doesn't work
This is because your window.onload is not done right. Take the parentheses off:
window.onload = setDiv;
http://jsfiddle.net/userdude/u8DZx/3/
I want to demonstrate how easy this is to do in a library like jQuery. window.onload does not always work the way you think either; it's often better to use onDomReady, or $(document).ready() in jQuery. You can also add multiple handlers at different points in the page load, which is more difficult just using the window.onload method.
$(document).ready(function(){
setTimeout(function(){setDiv();},2000); // So you can see the transition
});
function setDiv() {
var $sidebar = $('#sidebar');
if ($sidebar.size() === 0) {
return true;
} else {
$('#result').animate({
height : $('#sidebar').height()
}, 5000);
return false;
}
}
http://jsfiddle.net/userdude/u8DZx/1/
If you don't want the effect, just do:
$('#result').height($('#sidebar').height());
And if you actually meant to use offsetHeight, which it doesn't sound like that's what you want (height instead), you could do this:
$(document).ready(function(){
setTimeout(function(){setDiv();},2000); // So you can see the transition
});
function setDiv() {
var $sidebar = $('#sidebar');
if ($sidebar.size() === 0) {
return true;
} else {
$('#result').offset($('#sidebar').offset());
return false;
}
}
http://jsfiddle.net/userdude/u8DZx/2/
Say I have Div1 and Div2. I want to make that when a user is dragging around Div1, Div2 should also drag along. Any ideas how do I make it?
Here's what I got so far...
$(document).ready(function() {
$("#apDiv1").draggable();
$("#apDiv2").draggable(); //<- how do I link it do Div1 ?
});
EDIT ------------------------------------------------------------------
Thanks, I looked into the docs and got so far:
<script>
$(document).ready(function() {
$("#apDiv1").draggable();
});
$( "#apDiv1" ).bind( "drag", function(event, ui) {
$( "#apDiv2" ).css({ top: event.offsetY, left: event.offsetX });
</script>
Seems to be right, but... hmm, isn't' working. any ideas?
have a look at http://docs.jquery.com/UI/Draggable#event-drag to see how to bind to a draggable event. Bind the draggable event of div1 to a function that changes the coordinates of div2
Cheers.
Regarding your edit I've made some changes that can be viewed here http://jsfiddle.net/9FrXr/2/
You weren't closing the "drag" bind and instead of event.offsetY and event.offsetX I've used ui.offset.top and ui.offset.x. The drag bind has also been moved into the document.ready function.
$("#apDiv1").bind( "drag", function(event, ui) {
div.css({ top: ui.offset.top + 52, left: ui.offset.left });
});
// JavaScript Document
//This is an easy draggable javascript frameworkt
//There is no license for it so you can modify it how ever you like
//Coding started: 2011-05-28 and finished 2011-05-09
//The code can contain bugs. I only use an array to store the ID:s of the draggables
//Create an array for the draggers// I am not using an class because it is not nesesery for this easy thing
/////////////////////////////////////////////////////////////////////////////////////////////////////////
var Elements=new Array('draggable2','draggable3','draggable4','draggable5','draggable6','draggable7','draggable8','draggable9','draggable10');
//Set ID wher to do select disabeled
var textDisabling="body";
//Set drag TAG exeption//
var dragException=new Array('input','SPAN');
//////////////////////////////////////Start the framework
document.onmousemove=drag;
document.onmousedown=mouseDown;
document.onmouseup=mouseUp;
var parent;
//Offset vars//
var offsetY,offsetX;
//Setup the timeout event holder here//
var timeout=null;
//Set a var that will hold the dragged object//
var ObjectDrag;
//Set boolean vars to elerate//
var clickStage=true;
var XPos, YPos;//<--Setting up the position vars//
//////////////////////////////////////
//Get the browser name for your own needs//
//////////////////////////////////////
function getBrowserName(){
var Navigator=navigator.userAgent;
if(Navigator.indexOf("MSIE")>=0){
Navigator="MSIE";
}else if(Navigator.indexOf("Netscape")>=0){
Navigator="Netscape";
}else if(Navigator.indexOf("Firefox")>=0){
Navigator="Firefox";
}else if(Navigator.indexOf("Opera")>=0){
Navigator="Opera";
}else if(Navigator.indexOf("Safari")>=0){
Navigator="Safari";
}else{
Navigator="NULL";
}//IF
return Navigator;
}//Function
//END//
/////////////////////////////////////
//Get browser version to your neads//
/////////////////////////////////////
function getBrowserVersion(){
var browserName=getBrowserName(),
findIndex,
browserVersion;
browserVersion=navigator.userAgent;
findIndex=browserVersion.indexOf(browserName) + browserName.length+1;
browserVersion=parseFloat(browserVersion.substr(findIndex,findIndex + 3));
return browserVersion;
}//Function
//END//
function getMousePos(event){
var event=event || window.event;
//Get the position of the mouse with an offset of the top page
//////////////////////////////////////////////////////////////
if(event.pageX && event.pageY){
//We get the mouse position in newer browsers//
XPos=event.pageX;
YPos=event.pageY;
}else{
//We gat the same value as abow, but this is for older browsers//
XPos=event.clientX + document.body.scrollLeft - document.body.clientLeft;
YPos=event.clientY + document.body.scrollTop - document.body.clientTop;
}
//This is only for debugging the mouse position//
document.getElementById('X').value=XPos;/////////
document.getElementById('Y').value=YPos;/////////
return {XPos:XPos, YPos:YPos};
}
//Function for disabling text selections//
function disableTextSelection(event){
var event=event || window.event;
var object;
if(getBrowserName() != "MSIE"){object=event.target;}else{object=event.srcElement;}
if (typeof document.getElementById(textDisabling).onselectstart!="undefined"){ //IE route
document.getElementById(textDisabling).onselectstart=function(){return false}
object.onselectstart=function(){return false}
}else if (typeof document.getElementById(textDisabling).style.MozUserSelect!="undefined"){ //Firefox route
document.getElementById(textDisabling).style.MozUserSelect="none"
object.style.MozUserSelect="none"
}else{ //All other route (ie: Opera)
document.getElementById(textDisabling).onmousedown=function(){return false}
object.onmousestart=function(){return false}
}
}
//Allow text selection funtion. Call this when you do muse up//
function allowTextSelection(){
if (typeof document.getElementById(textDisabling).onselectstart!="undefined"){ //IE route
document.getElementById(textDisabling).onselectstart=function(){return true}
ObjectDrag.onselectstart=function(){return true}
}else if (typeof document.getElementById(textDisabling).style.MozUserSelect!="undefined"){ //Firefox route
document.getElementById(textDisabling).style.MozUserSelect="text"
ObjectDrag.style.MozUserSelect="text"
}else{ //All other route (ie: Opera)
document.getElementById(textDisabling).onmousedown=function(){return true}
ObjectDrag.onmousestart=function(){return true}
}
}
//Setup the global function that we will start from//
function drag(event){
var mousePos=getMousePos(event);
}
//Make an exception function //
function exception(event){
if(getBrowserName() != "MSIE"){
for(items in dragException){if(event.target.nodeName == dragException[items].toUpperCase())return {contin:false};}
}else{
for(items in dragException){if(event.srcElement.nodeName == dragException[items].toUpperCase())return {contin:false};}
}
return true;
}
//This function checks if you are pulling the click inside the element
function isInside(event){
var event=event || window.event;
var object;
if(getBrowserName() != "MSIE"){object=event.target;}else{object=event.srcElement;}
if(object.nodeName=="HTML")return false;
parent=object;
var i,l=0;
for(i=0;i<=l;i++){
if(parent.nodeName != "BODY"){
for(items in Elements){
if(Elements[items] == parent.id){
return {contin:true, id:parent};
}
}
parent=parent.parentNode;
l++;
}else{
return false;
}
}
}
//Here we get the offset position so the element will follow the mouse where you
//did (mouseDown) event. If we noe capturing the offset, the element will lie line to line with the
//mouse. NO OFFSET
function offsetObject(YPos,XPos){
offsetY=YPos-ObjectDrag.offsetTop;
offsetX=XPos-ObjectDrag.offsetLeft;
return false;
}
//Set the objects on a good z-index//
function setZIndex(event){
var event=event || window.event;
var object;
if(getBrowserName() != "MSIE"){object=event.target;}else{object=event.srcElement;}
for(items in Elements){
document.getElementById(Elements[items]).style.zIndex="1";
}
object.style.zIndex="20";
}
//Capture mouse down//
function mouseDown(event){
var event=event || window.event;
/*if(getBrowserName() != "MSIE"){ */
timeout=null;
clickStage=true;
//Store the event if it´s not null and can be dragged//
var inside=isInside(event);
if(inside.contin == true && exception(event) == true){
/*Function that disables the text selection on drag*/
disableTextSelection(event);
ObjectDrag=inside.id;
offsetObject(YPos,XPos);
//Set the z-indexes//
setZIndex(event);
moveObject();
}
/*}else{
alert("Browser is not suported");
}*/
}
//Start moving the object//
function moveObject(){
//Stor the mouse event in this var//
if(clickStage == true)timeout=setTimeout(moveObject,0);
//Change it back to true if the mouseUp event has not trigged//
clickStage=true;
//Store the event if it´s not null and can be dragged//
if(clickStage==true){
//This is the place where we set the position of the element
document.getElementById(ObjectDrag.id).style.left=XPos-offsetX+"px";
document.getElementById(ObjectDrag.id).style.top=YPos-offsetY+"px";
}
}
//Capture mouse up//
function mouseUp(event){
var event=event || window.event;
if(exception(event) == true ){
allowTextSelection();
timeout=null;
clickStage=false;
}
}
Thanks again, got it fully working on the webpage. You can see it in action by moving the menu around at www[dot]skyeye[dot]cc .
<script>
$(function() {
$("#apDiv3").draggable();
$("#apDiv3").bind("drag", function(event, masterdrag) {
$("#apDiv5").css({ top: masterdrag.offset.top, left: masterdrag.offset.left-20 });
});
});
</script>