I'm writing code that handles the resize event, and ran into some trouble.
Here is the code:
/*
Timeline.js
(Requires jquery, developed with jquery-1.4.4.min.js in mind)
*/
/*
Timeline's two major functions are setup and draw. After instantiating a
timeline object, the developer calls setup() to initialize the object. Later,
the developer repeatedly calls on draw() to animate the canvas.
In between, resizing the window may trigger the resize() function which
adjusts the timeline's dimensions and other settings.
*/
function Timeline(){
// constants
Timeline._BORDER_SIDES = 20; // The border on each side of the timeline,
// We'll need this value later when calculating back's top offset
Timeline._OFFSET_LEFT = '8px';
Timeline._OFFSET_TOP = '8px'; // top border, 8px seems to be chrome default
Timeline._BUTTON_WIDTH = 17; // The length of the back and forward buttons
Timeline._WIDTH_FACTOR = 2/3; // How much height timeline should take up
// variables
Timeline._id = 0; // An id wich is unique for each instance of Timeline
/* This function is called when the user clicks the back div*/
this._backHandler = function(){
alert('back clicked');
};
this._testResize = function(){
alert('resized');
};
/*
timeline.setup()
Create canvas, back and forward button, as well as slider for scale.
timeline_wrapper_id is the id of an element which is to contain this
specific timeline.
*/
this.setup = function(timeline_wrapper_id){
// add canvas
this._id = Timeline._id++; // get id, create next id for next instance
this._timeline_wrapper_id = timeline_wrapper_id;
this._canvas = document.createElement('canvas');
this._canvas.setAttribute('id', 'canvas' + this._id);
$('#' + timeline_wrapper_id).append(this._canvas);
// add back button
this._back = document.createElement('div');
this._back.setAttribute('id', 'back' + this._id);
// id's help us jquery stuff, ensuring their unique across instances
// lets us potentially put several instance on the same page.
this._back.onclick = this._backHandler; // set event handler: onclick
$('#' + timeline_wrapper_id).append(this._back);
this._resizeHandler = function(){
// First, we clear all style so as to prevent duplicates
$('#canvas' + this._id).removeAttr('style');
$('#back' + this._id).removeAttr('style');
// later we'll insert an empty style before modifying the style.
// set canvas attributes
// Width of canvas is window width, with space for borders either
// side.
var canvas_width = $(window).width() - Timeline._BORDER_SIDES*2;
var canvas_height = $(window).height() * Timeline._HEIGHT_FACTOR;
/* The core feature of this block is the z-index. Everything else
is there because otherwise I can't determine the z-index. At
least that's what I read somewhere.
The z-index determines how overlapping elements are drawn.
The higher the z-index, the "closer to the user" the element is.
In this case, we want to draw everything on top of the canvas,
hence the lowest z-index in our application: 0.
*/
$('#canvas'+this._id).attr('style', '');
// this undoes our removeAttr('style') from earlier
$('#canvas' + this._id).css({
width: canvas_width,
height: canvas_height,
border: '1px solid', // to see what's going on
position: 'relative', // "take canvas out of flow"-rough quote
top: Timeline._BORDER_TOP, // seems to be the chrome default
left: Timeline._BORDER_LEFT, // ditto
'z-index': 0
});
/* Here we define the back button's visual properties.
Where possible, we calculate them in terms of canvas attributes,
to achieve a consistent layout as the browser is resized.
*/
var back_left = $('#canvas' + this._id).css('left') + 'px';
// same distance from left timeline_wrapper as canvas
// This one is a little more difficult: An explanation will follow
// as soon as I've figured it out myself.
var back_top = ((-1)*$('#canvas' + this._id).height() - 6) + 'px';
$('#back' + this._id).attr('style', '');
$('#back' + this._id).css({
'background-color': '#336699',
width: Timeline._BUTTON_WIDTH,
height: $('#canvas' + this._id).height(), // fill canvas height
position: 'relative', // same reason as for canvas
left: back_left,
top: back_top,
'z-index': 1
});
};
this._resizeHandler();
$(window).resize(this._resizeHandler);
};
/*
timeline.draw()
Update (or set for the first time) the styles of back and forward button,
as well as the canvas.
Assumes setup has been called.
*/
this.draw = function(){
console.log('dummy');
};
}
The code calling Timeline.js is pretty simple:
<!doctype html>
<html>
<head>
<title>timeline-js</title>
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="Timeline.js"></script>
</head>
<body>
<div id="timeline_wrapper"></div>
<script type="text/javascript">
var timeline = new Timeline();
timeline.setup('timeline_wrapper');
// timeline.draw();
//setInterval('timeline.draw()', 60);
</script>
</body>
</html>
The resize function doesn't throw any errors in Chrome, and works when called like so:
this._resizeHandler();
The error handler is called, I know that because setting window.onresize = this._testReszie works fine, too.
However, when I combine the two, the canvas doesn't resize with the window.
Can someone point me in the right direction here?
The problem is that, in your _resizeHandler function, this does not refer to your Timeline instance. Instead it refers to window since that's what the handler has been attached to.
On way of fixing it (and this is not the only way) is to redefine _resizeHandler so that it gets a reference to the Timeline instance.
this._resizeHandler = function(self){
...same code but with 'this' replaced by 'self'...
}
And then fix up the call sites:
this._resizeHandler(this);
var thisTimeline = this;
$(window).resize(function() { thisTimeline._resizeHandler(thisTimeline); });
};
Related
I use a Zoom JavaScript for zoom my images when I click on it.
This JavaScript creates a hidden copy of my image with bigger dimensions.
Problem is, when I load my page, the body takes a height and width according to the hidden image.
You can see at the right of the screen the menu doesn't fit with the width of the screen (the hidden image is not displayed).
Is there a solution when I load the page, the size of the body does not take into account the hidden image?
// To achieve this effect we're creating a copy of the image and scaling it up. Next we'll pull the x and y coordinates of the mouse on the original image. Then we translate the big image so that the points we are looking at match up. Finally we create a mask to display the piece of the image that we're interested in.
let settings = {
'magnification': 3,
'maskSize': 200
}
// Once our images have loaded let's create the zoom
window.addEventListener("load", () => {
// find all the images
let images = document.querySelectorAll('.image-zoom-available');
// querySelectorAll produces an array of images that we pull out one by one and create a Zoombini for
Array.prototype.forEach.call(images, (image) => {
new Zoombini(image);
});
});
// A Zoombini (or whatever you want to call it), is a class that takes an image input and adds the zoomable functionality to it. Let's take a look inside at what it does.
class Zoombini {
// When we create a new Zoombini we run this function; it's called the constructor and you can see it taking our image in from above
constructor(targetImage) {
// We don't want the Zoombini to forget about it's image, so let's save that info
this.image = targetImage;
// The Zoombini isActive after it has opened up
this.isActive = false;
// But as it hasn't been used yet it's maskSize will be 0
this.maskSize = 0;
// And we have to start it's coordinates somewhere, they may as well be (0,0)
this.mousex = this.mousey = 0;
// Now we're set up let's build the necessary compoonents
// First let's clone our original image, I'm going to call it imageZoom and save it our Zoombini
this.imageZoom = this.image.cloneNode();
// And pop it next to the image target
this.image.parentNode.insertBefore(this.imageZoom, this.image);
// Make the zoom image that we'll crop float above it's original sibling
this.imageZoom.style.zIndex = 1;
// We don't want to be able to touch it though, we want to reach whats underneat
this.imageZoom.style.pointerEvents = "none";
// And so we can translate it let's make it absolute
this.imageZoom.style.position = "absolute";
// Now let's scale up our enlarged image and add an event listener so that it resizes whenever the size of the window changes
this.resizeImageZoom();
window.addEventListener("resize", this.resizeImageZoom.bind(this), false);
// Now that we're finishing the constructor we need to addeventlisteners so we can interact with it
// This function is just below, but still exists within our Zoombini
this.UI();
// Finally we'll apply an initial mask at default settings to hide this image
this.drawMask();
}
// resizeImageZoom resizes the enlarged image
resizeImageZoom() {
// So let's scale up this version
this.imageZoom.style.width = this.image.getBoundingClientRect().width * settings.magnification + 'px';
this.imageZoom.style.height = "unset"
}
// This could be inside the constructor but it's nicer on it's own I think
UI() {
this.image.addEventListener('mousemove', (event) => {
// When we move our mouse the x and y coordinates from the event
// We subtract the left and top coordinates so that we get the (x,y) coordinates of the actualy image, where (0,0) would be the top left
this.mousex = event.clientX - this.image.getBoundingClientRect().left;
this.mousey = event.clientY - this.image.getBoundingClientRect().top;
// if we're not active then don't display anything
if (!this.isActive) return;
// The drawMask() function below displays our the portion of the image that we're interested in
this.drawMask();
});
// When they mousedown we open up our mask
this.image.addEventListener('mousedown', () => {
// But it can be opening or closing, so let's pass in that information
this.isExpanding = true;
// To do that we start the maskSizer function, which calls itself until it reaches full size
this.maskSizer();
// And hide our cursor (we know where it is)
this.image.classList.add('is-active');
});
// if the mouse is released, close the mask
this.image.addEventListener('mouseup', () => {
// if it's not expanding, it's closing
this.isExpanding = false;
// if the mask has already expanded we'll need to start another maskSizer to shrink it. We don't run the maskSizer unless the mask is changing
if (this.isActive) this.maskSizer();
});
// same as above, caused by us moving out of the zoom area
this.image.addEventListener('mouseout', () => {
this.isExpanding = false;
if (this.isActive) this.maskSizer();
});
}
// The drawmask function shows us the piece of the image that we are hovering over
drawMask() {
// Let's use getBoundingClientRect to get the location of our images
let image = this.image.getBoundingClientRect();
let imageZoom = this.imageZoom.getBoundingClientRect();
// We'll start by getting the (x,y) of our big image that matches the piece we're mousing over (which we stored from our event listener as this.mousex and this.mousey). This is a clunky bit of code to help the zooms work in a variety of situations.
let prop_x = this.mousex / image.width * imageZoom.width * (1 - 1 / settings.magnification) - image.x - window.scrollX;
let prop_y = this.mousey / image.height * imageZoom.height * (1 - 1 / settings.magnification) - image.y - window.scrollY;
// Shift the large image by that amount
this.imageZoom.style.left = -prop_x + "px";
this.imageZoom.style.top = -prop_y + "px";
// Now we need to create our mask
// First let's get the coordinates of the point we're hovering over
let x = this.mousex * settings.magnification;
let y = this.mousey * settings.magnification;
// And create and apply our clip
let clippy = "circle(" + this.maskSize + "px at " + x + "px " + y + "px)";
this.imageZoom.style.clipPath = clippy;
this.imageZoom.style.webkitClipPath = clippy;
}
// We'll use the maskSizer to either expand or shrink the size of our mask
maskSizer() {
// We're in maskSizer so we're changing the size of our mask. Let's make the mask radius larger if the Zoombini is expanding, or shrink it if it's closing. The numbers below might need to be adjusted. It closes faster than it opens
this.maskSize = this.isExpanding ? this.maskSize + 35 : this.maskSize - 40;
// It has the form of: condition ? value-if-true : value-if-false
// Think of the ? as "then" and : as "else"
// if we've reaached max size, don't make it any larger
if (this.maskSize >= settings.maskSize) {
this.maskSize = settings.maskSize;
// we'll no longer need to change the maskSize so we'll just set this.isActive to true and let our mousemove do the drawing
this.isActive = true;
} else if (this.maskSize < 0) {
// Our mask is closed
this.maskSize = 0;
this.isActive = false;
this.image.classList.remove('is-active');
} else {
// Or else we haven't reached a size that we want to keep yet. So let's loop it on the next available frame
// We bind(this) here because so that the function remains in context
requestAnimationFrame(this.maskSizer.bind(this));
}
// After we have the appropriate size, draw the mask
this.drawMask();
}
}
function zoom(e) {
var zoomer = e.currentTarget;
e.offsetX ? offsetX = e.offsetX : offsetX = e.touches[0].pageX
e.offsetY ? offsetY = e.offsetY : offsetX = e.touches[0].pageX
x = offsetX / zoomer.offsetWidth * 100
y = offsetY / zoomer.offsetHeight * 100
zoomer.style.backgroundPosition = x + '% ' + y + '%';
}
//My image generated after page load
.image-zoom-available {
height: unset;
border-radius: 30px;
z-index: 1;
pointer-events: none;
position: absolute;
width: 834.688px;
left: 526.646px;
top: 231.729px;
clip-path: circle(0px at 439.062px 987.812px);
}
<div class="col-12 col-xl-3 col-lg-5 justify-content-center ">
<div class="mb-3">
<img class="image-zoom-available" style="height:75%; border-radius: 30px" src='{{ asset(' /radio/ ') }}{{examen.idpatient.id}}_examen_{{examen.id}}_radio.png' id="image_radio" draggable="false" />
</div>
</div>
Try adding the following property in your hidden image css :
display: none
A non visible element still take space in the web page. Cf: What is the difference between visibility:hidden and display:none?
Remove or override the display: none property when you want to display the image.
I add
this.imageZoom.style.display = "none";
on the event : mouseup and
this.imageZoom.style.display = "block";
on mousedown event. And it's fix thanks !
I got an application where I'm moving an image around the page using CSS3 Animations the idea is you click a button and the next animation runs and this way the "sprite" moves around a map.
However on mobile I was asked to keep the size of the map the same as desktop but instead move the map instead of the sprite, my question is how can I make that work?
My current (really early) code looks like this:
$(document).on("boatAnimationStarted", function(event) {
window.isAnimating = true;
var boatElement = $("#boat-sprite");
var backgroundElement = $("#background");
var backgroundWidth = backgroundElement.width();
var backgroundHeight = backgroundElement.height();
var windowSize = { width: $(window).width(), height: $(window).height() };
var originalOffset = boatElement.offset();
window.animationInterval = setInterval(function() {
var boatOffset = boatElement.offset();
var working = {
top: originalOffset.top - (boatOffset.top / 2),
left: originalOffset.left - (boatOffset.left / 2),
}
$("#background").offset(working);
}, 10);
});
This does manage to move it somewhat but it doesn't seem to be exact and isn't really accounting for the offset of the #background element when it changes position.
So I'm guessing I should do everything relative to the Background image (which is around 1200w X 421h)
So to do that you would do something like this i'm guessing
var relativeOffset = {
top: boatOffset.top - backgroundElement.offset().top,
left: boatOffset.left - backgroundElement.offset().left
}
And I would in theory get the offsets of the sprite relative to the large background image as opposed to the mobile viewport. But then how would I go about moving the background?
Sorry if it's a simple question but it's the first time I've ever had to work with this kind of stuff so I'm a bit confused.
I have this event:
$(window).scroll(function(e){
console.log(e);
})
I want to know, how much I have scroll value in pixels, because I think, scroll value depends from window size and screen resolution.
Function parameter e does not contains this information.
I can store $(window).scrollTop() after every scroll and calculate difference, but can I do it differently?
The "scroll value" does not depend on the window size or screen resolution. The "scroll value" is simply the number of pixels scrolled.
However, whether you are able to scroll at all, and the amount you can scroll is based on available real estate for the container and the dimensions of the content within the container (in this case the container is document.documentElement, or document.body for older browsers).
You are correct that the scroll event does not contain this information. It does not provide a delta property to indicate the number of pixels scrolled. This is true for the native scroll event and the jQuery scroll event. This seems like it would be a useful feature to have, similar to how mousewheel events provide properties for X and Y delta.
I do not know, and will not speculate upon, why the powers-that-be did not provide a delta property for scroll, but that is out of scope for this question (feel free to post a separate question about this).
The method you are using of storing scrollTop in a variable and comparing it to the current scrollTop is the best (and only) method I have found. However, you can simplify this a bit by extending jQuery to provide a new custom event, per this article: http://learn.jquery.com/events/event-extensions/
Here is an example extension I created that works with window / document scrolling. It is a custom event called scrolldelta that automatically tracks the X and Y delta (as scrollLeftDelta and scrollTopDelta, respectively). I have not tried it with other elements; leaving this as exercise for the reader. This works in currrent versions of Chrome and Firefox. It uses the trick for getting the sum of document.documentElement.scrollTop and document.body.scrollTop to handle the bug where Chrome updates body.scrollTop instead of documentElement.scrollTop (IE and FF update documentElement.scrollTop; see https://code.google.com/p/chromium/issues/detail?id=2891).
JSFiddle demo: http://jsfiddle.net/tew9zxc1/
Runnable Snippet (scroll down and click Run code snippet):
// custom 'scrolldelta' event extends 'scroll' event
jQuery.event.special.scrolldelta = {
delegateType: "scroll",
bindType: "scroll",
handle: function (event) {
var handleObj = event.handleObj;
var targetData = jQuery.data(event.target);
var ret = null;
var elem = event.target;
var isDoc = elem === document;
var oldTop = targetData.top || 0;
var oldLeft = targetData.left || 0;
targetData.top = isDoc ? elem.documentElement.scrollTop + elem.body.scrollTop : elem.scrollTop;
targetData.left = isDoc ? elem.documentElement.scrollLeft + elem.body.scrollLeft : elem.scrollLeft;
event.scrollTopDelta = targetData.top - oldTop;
event.scrollTop = targetData.top;
event.scrollLeftDelta = targetData.left - oldLeft;
event.scrollLeft = targetData.left;
event.type = handleObj.origType;
ret = handleObj.handler.apply(this, arguments);
event.type = handleObj.type;
return ret;
}
};
// bind to custom 'scrolldelta' event
$(window).on('scrolldelta', function (e) {
var top = e.scrollTop;
var topDelta = e.scrollTopDelta;
var left = e.scrollLeft;
var leftDelta = e.scrollLeftDelta;
// do stuff with the above info; for now just display it to user
var feedbackText = 'scrollTop: ' + top.toString() + 'px (' + (topDelta >= 0 ? '+' : '') + topDelta.toString() + 'px), scrollLeft: ' + left.toString() + 'px (' + (leftDelta >= 0 ? '+' : '') + leftDelta.toString() + 'px)';
document.getElementById('feedback').innerHTML = feedbackText;
});
#content {
/* make window tall enough for vertical scroll */
height: 2000px;
/* make window wide enough for horizontal scroll */
width: 2000px;
/* visualization of scrollable content */
background-color: blue;
}
#feedback {
border:2px solid red;
padding: 4px;
color: black;
position: fixed;
top: 0;
height: 20px;
background-color: #fff;
font-family:'Segoe UI', 'Arial';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='feedback'>scrollTop: 0px, scrollLeft: 0px</div>
<div id='content'></div>
Note that you may want debounce the event depending on what you are doing. You didn't provide very much context in your question, but if you give a better example of what you are actually using this info for we can provide a better answer. (Please show more of your code, and how you are using the "scroll value").
To detemine how many pixels were scrolled you have to keep in mind that the scroll event gets fired almost every pixel that you move. The way to accomplish it is to save the previous scrolled value and compare that in a timeout. Like this:
var scrollValue = 0;
var scrollTimeout = false
$(window).scroll(function(event){
/* Clear it so the function only triggers when scroll events have stopped firing*/
clearTimeout(scrollTimeout);
/* Set it so it fires after a second, but gets cleared after a new triggered event*/
scrollTimeout = setTimeout(function(){
var scrolled = $(document).scrollTop() - scrollValue;
scrollValue = $(document).scrollTop();
alert("The value scrolled was " + scrolled);
}, 1000);
});
This way you will get the amount of scrolled a second after scrolling (this is adjustable but you have to keep in mind that the smooth scrolling that is so prevalent today has some run-out time and you dont want to trigger before a full stop).
The other way to do this? Yes, possible, with jQuery Mobile
I do not appreciate this solution, because it is necessary to include heavy jQuery mobile. Solution:
var diff, top = 0;
$(document).on("scrollstart",function () {
// event fired when scrolling is started
top = $(window).scrollTop();
});
$(document).on("scrollstop",function () {
// event fired when scrolling is stopped
diff = Math.abs($(window).scrollTop() - top);
});
To reduce the used processing power by adding a timer to a Jquery scroll method is probably not a great idea. The visual effect is indeed quite bad.
The whole web browsing experience could be made much better by hiding the scrolling element just when the scroll begins and making it slide in (at the right position) some time after. The scrolling even can be checked with a delay too.
This solution works great.
$(document).ready(function() {
var element = $('.movable_div'),
originalY = element.offset().top;
element.css('position', 'relative');
$(window).on('scroll', function(event) {
var scrollTop = $(window).scrollTop();
element.hide();
element.stop(false, false).animate({
top: scrollTop < originalY
? 0
: scrollTop - originalY + 35
}, 2000,function(){element.slideDown(500,"swing");});
});
});
Live demo here
I'm making colored squares to fill a browser window (say, 20px by 20px repeated horizontally and vertically).
There are 100 different colors, each link to a different link (blog post relevant to that color).
I want to fill the browser window with at least 1 of each colored square, and then repeat as necessary to fill the window, so that there are colored squares on the whole background, as the user drags the window smaller and larger.
If these were just images, setting a repeatable background would work. But, I would like them to be links. I'm not sure where to start on this. Any ideas, tips?
Here's the link to the site I'm working on: http://spakonacompany.com/
I think the most specific piece I need here is this: how can I determine the number of squares needed to repeat to fill the background, using jQuery that dynamically calculates that using the size of the browser window, including when dragged, resized, etc?
Many thanks. :)
To get browser's window width and height I use this function ->
//checking if the browser is Internet Explorer
var isIEX = navigator.userAgent.match(/Trident/);
var doc = isIEX ? document.documentElement : document.body;
function getwWH() {
var wD_ = window;
innerW = wD_.innerWidth || doc.clientWidth;
innerH = wD_.innerHeight || doc.clientHeight;
return {iW:innerW, iH:innerH}
}
There is also a native method of detecting when the browser's window is being resized which works in all major browsers (including IE 8, if you're planning on supporting it) ->
window.onresize = function(){
//here goes the code whenever the window is getting resized
}
So, in order to define how many squares are required to fill the window, you can get the window's width and divide it by the width of the square you are going to fill the window with ->
//getting total number of squares for filling the width and the height
width_ = getwWH().iW; //the width of the window
height_ = getwWH().iH; //the height of the window
If your square's width and height are static 20 by 20, than we can calculate total number of squares per window by dividing our width_ variable by 20 (the same for the height_) ->
squaresPerWidth = width_/20;
squaresPerHeight = height_/20;
So every time our browser window is getting resized we do this ->
window.onresize = function(){
width_ = getwWH().iW;
height_ = getwWH().iH;
squaresPerWidth = width_/20;
squaresPerHeight = height_/20;
//and the rest of the code goes here
}
Haven't tested it but this should work.
Here's something I whipped up. It uses a fixed number of resizable squares, but if you need squares of a fixed size, you just set the window to overflow: hidden and generate an unreasonably large number of squares.
var fillGrid = function(getColor, onClick) {
var tenTimes = function(f){
return $.map(new Array(10),
function(n, i) {
return f(i);
});
};
var DIV = function() {
return $('<div></div>');
};
var appendAll = function(d, all) {
$.map(all, function(e) {
d.append(e);
});
return d;
};
appendAll($('body'),
tenTimes(function(col) {
return appendAll(DIV().css({ height : "10%" }),
tenTimes(function(row) {
return DIV().css({
height : "100%",
width : "10%",
backgroundColor: getColor(row, col),
'float' : "left"
}).click(function() { onClick(row, col); });
}));
}));
};
You have to supply two functions, one to specify the color, the other to be invoked when the user clicks.
On my website, I have a sidebar DIV on the left and a text DIV on the right. I wanted to make the sidebar follow the reader as he or she scrolls down so I DuckDuckGo'ed a bit and found this then modified it slightly to my needs:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(function(){
var $sidebar = $('#sidebar'),
sidebarOffset = $sidebar.offset(),
$window = $(window),
gap = $('#header').css('marginBottom').replace(/[^-\d\.]/g, ''),
distance = ($window.scrollTop()) - (sidebarOffset.top - gap),
footerHeight = $('#footer').outerHeight();
$window.scroll(function(){
distance = ($window.scrollTop()) - (sidebarOffset.top - gap);
if ( distance > 0 ) {
$sidebar.css({'top': gap + 'px', 'position' : 'fixed'});
} else {
$sidebar.css({'top': '0', 'position': 'relative'});
}
})
});
});//]]>
</script>
And it works just like I want it to. However, my website uses Skeleton framework to handle responsive design. I've designed it so that when it goes down to mobile devices (horizontal then vertical), sidebar moves from being to the left of the text to being above it so that text DIV can take 100% width. As you can probably imagine, this script causes the sidebar to cover parts of text as you scroll down.
I am completely new to jQuery and I am doing my best through trial-and-error but I've given up. What I need help with is to make this script not execute if a certain DIV has a certain CSS value (i.e. #header-logo is display: none).
Ideally, the script should check for this when user resizes the browser, not on website load, in case user resizes the browser window from normal size to mobile size.
I imagine it should be enough to wrap it in some IF-ELSE statement but I am starting to pull the hair out of my head by now. And since I don't have too much hair anyway, I need help!
Thanks a lot in advance!
This function will execute on window resize and will check if #header-logo is visible.
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
// Your code
}
});
I think you need to check this on load to, because you don't know if the user will start with mobile view or not. You could do something like this:
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
// Your code
}
}).resize();
This will get executed on load and on resize.
EDIT: You will probably need to turn off the scroll function if #header-logo is not visible. So, instead of create the function inside the scroll event, you need to create it outside:
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
var $sidebar = $('#sidebar'),
sidebarOffset = $sidebar.offset(),
$window = $(window),
gap = $('#header').css('marginBottom').replace(/[^-\d\.]/g, ''),
distance = ($window.scrollTop()) - (sidebarOffset.top - gap),
footerHeight = $('#footer').outerHeight();
function myScroll() {
distance = ($window.scrollTop()) - (sidebarOffset.top - gap);
if ( distance > 0 ) {
$sidebar.css({'top': gap + 'px', 'position' : 'fixed'});
} else {
$sidebar.css({'top': '0', 'position': 'relative'});
}
}
$window.on('scroll', myScroll);
} else {
$(window).off('scroll', myScroll);
}
});
Didn't test it, but you get the idea.
$("#headerLogo").css("display") will get you the value.
http://api.jquery.com/css/
I also see you only want this to happen on resize, so wrap it in jquery's resize() function:
https://api.jquery.com/resize/