simple javascript if statement not working - javascript

I have a simple script inside my html file that changes the opacity of a div depending on the result of the $(window).scrollTop() function. So if I scroll over a certain point the div appears and if I scroll back behind that point it should disappear again.
This works fine:
$(window).scroll(function () {
if ($(window).scrollTop() > $("#m-product-sweater").offset().top) {
$("#m-nav").animate({opacity: "1"}, 500);
};
});
The logic for changing the opactiy back to 0 is missing. So I simply changed the code to:
$(window).scroll(function () {
if ($(window).scrollTop() > $("#m-product-sweater").offset().top) {
$("#m-nav").animate({opacity: "1"}, 500);
};
if ($(window).scrollTop() < $("#m-product-sweater").offset().top) {
$("#m-nav").animate({opacity: "0"}, 500);
};
});
All of the sudden the whole script won't work anymore! Why?
I don't see any mistakes. I also tried it with else like this:
$(window).scroll(function () {
if ($(window).scrollTop() > $("#m-product-sweater").offset().top) {
$("#m-nav").animate({opacity: "1"}, 500);
} else {
$("#m-nav").animate({opacity: "0"}, 500);
};
});
Won't work either. I am stuck. :(

It's a small thing, but your code currently re-hides the same element every time the window scrolls. You might want to consider modifying your if statement to be slightly more selective:
var toggleMe = $("#m-nav");
$(window).scroll(function() {
var myWindowTop = $(document).scrollTop();
var myContentTop = $(".content-pane").offset().top;
// I'm checking the scroll position AND
// the visibility of my toggled div.
// This way, the if statement only runs
// once rather than constantly stacking.
if (myWindowTop > myContentTop && toggleMe.css("opacity") == "0") {
console.log("showMe!");
toggleMe.animate({
opacity: "1"
}, 500);
} else
// I'm checking the scroll position AND
// the visibility of my toggled div.
// This way, the if statement only runs
// once rather than constantly stacking.
if (myWindowTop < myContentTop && toggleMe.css("opacity") == "1") {
console.log("hideMe!");
toggleMe.animate({
opacity: "0"
}, 500);
}
});
.content-pane {
border: 1px dotted red;
}
.content-pane p {} #m-nav {
position: fixed;
top: 20px;
left: 5px;
background-color: #ccc;
border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Quisque velit nisi, pretium ut lacinia in, elementum id enim. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Proin eget tortor risus. Curabitur non nulla sit amet nisl tempus
convallis quis ac lectus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus.</p>
<div class="content-pane">
<p>Quisque velit nisi, pretium ut lacinia in, elementum id enim. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Proin eget tortor risus. Curabitur non nulla sit amet nisl
tempus convallis quis ac lectus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus.</p>
<p>Donec rutrum congue leo eget malesuada. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Vivamus suscipit tortor eget felis porttitor volutpat. Donec sollicitudin molestie
malesuada. Nulla porttitor accumsan tincidunt.</p>
<p>Proin eget tortor risus. Vivamus suscipit tortor eget felis porttitor volutpat. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Pellentesque in ipsum id orci porta dapibus. Vestibulum ac diam sit amet quam vehicula elementum sed sit
amet dui. Quisque velit nisi, pretium ut lacinia in, elementum id enim.</p>
<p>Quisque velit nisi, pretium ut lacinia in, elementum id enim. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Proin eget tortor risus. Curabitur non nulla sit amet nisl
tempus convallis quis ac lectus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus.</p>
<p>Donec rutrum congue leo eget malesuada. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Vivamus suscipit tortor eget felis porttitor volutpat. Donec sollicitudin molestie
malesuada. Nulla porttitor accumsan tincidunt.</p>
<p>Proin eget tortor risus. Vivamus suscipit tortor eget felis porttitor volutpat. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Pellentesque in ipsum id orci porta dapibus. Vestibulum ac diam sit amet quam vehicula elementum sed sit
amet dui. Quisque velit nisi, pretium ut lacinia in, elementum id enim.</p>
</div>
<div id="m-nav">
<h2>
FOO BAR FOO BAR
</h2>
</div>

I didn't look to deep into it yet but at first glance my instinct says it should be an if and else if.
$(window).scroll(function () {
if ($(window).scrollTop() > $("#m-product-sweater").offset().top) {
$("#m-nav").animate({opacity: "1"}, 500);
};
else if ($(window).scrollTop() < $("#m-product-sweater").offset().top) {
$("#m-nav").animate({opacity: "0"}, 500);
};
});
You may also want to play choose something other than .offset().top for the second thing because then it may be trying to do both of them at the same spot since they're both referencing the top of the div I believe.
Edit: As some are commenting, changing the > & < may also correct it.

Related

How to vertically slide off layers of an image off as the user scrolls down?

If anyone remembers the Apple product page for the cylindrical Mac Pro, the site had a feature that had each layer of the Mac Pro slide off as you continue to scroll down.
I have been looking everywhere for possible indication as to how to code this dynamic page, but I have been unsuccessful.
You can create the animation with CSS class and #keyframes rule, then add the class to your element once it reaches the scroll threshold you set in the conditional within a scroll event listener. Below is not an exact replica of Apples animation, however it will illustrate how one could achieve this with vanilla JS and CSS animations tween.
I further explain how I have done this in the code below...
// get the selector nodes we wish to animate
const images = document.querySelectorAll('#main img');
// create a function and pass in the selector node and the top
// fold position (how far off the top fold you wish to slideOut) as a param
const slideOut = (images, foldPos) => {
// run each element in the nodeList through a loop
images.forEach((el) => {
// add a scroll eventlistener on the window
window.addEventListener('scroll', () => {
// define each elements position using the forEach loop
// el.getBoundingClientRect and get the top position
let elPos = el.getBoundingClientRect().top;
// get the unique ID that was set in the elements we wish to animate
// we'll use this to get the element selector using its ID
let elId = el.id;
// conditional that checks the top position in
// relation to the top fold of page, this will pass
// as a parameter in the main function slideOut()
if (elPos < foldPos) {
// lets target the id selector of the animated element
// that has reached the set threshhold
let slideEl = document.getElementById(el.id);
// lets add our class to the element so the CSS can
// do its animation using an #keyframes rule
// * see the css code `.slideoff` and its `#keyframes` `slideoff` rule
slideEl.className = 'slideoff';
// optional, remove element from display using a timeOut()
// set to work in conjuntion with the CSS animation duration
setTimeout(() => slideEl.style.display = 'none', 500)
}
})
})
}
// call function and pass in the paramter (nodeList, topFoldThreshold)
slideOut(images, 125)
#main {
position: relative;
}
p {
max-width: 50%;
}
#main img {
width: 50%;
height: 50%;
}
.slideoff {
position: relative;
animation: slideoff 1s ease-in-out;
left: 50;
opacity: 0;
height: 50%;
width: 50%;
}
#keyframes slideoff {
0% {
opacity: 1;
top: 0;
left: 0;
}
50% {
opacity: 0;
top: 500px;
}
100% {
left: 10000px;
}
}
SCROLL DOWN
<p> Sed augue metus, iaculis non congue a, convallis ut sem. Etiam pulvinar est lorem, non fringilla velit aliquet sit amet. Cras vel eleifend nisl. Suspendisse vitae elit efficitur orci lacinia porta. Aliquam sed quam id velit mattis molestie. Aliquam id
ultricies velit, eu dictum purus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ac porttitor tortor.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nec interdum elit. Praesent eu dui mi. Vestibulum facilisis elit in mi convallis, eget consectetur arcu vehicula. Pellentesque ultricies elit tellus, non ultrices erat volutpat at.
Ut dui dolor, tempor nec porta at, aliquet eget urna. Etiam congue vestibulum ante. In et diam sapien. Suspendisse mattis eros eget ex convallis, nec tempor risus lobortis. Quisque ullamcorper libero arcu, quis ultrices magna aliquet non. Donec et ornare
eros. Proin viverra metus enim, vitae egestas tellus lacinia eu. Aenean molestie sollicitudin augue, placerat cursus enim consequat eu. Aenean semper pellentesque augue. Phasellus vel dictum neque. Donec vel imperdiet nisi. Ut sapien turpis, mattis
quis lobortis ut, placerat eget metus.
</p>
<div id="main">
<img id="first" src="https://www.pixelstalk.net/wp-content/uploads/2016/07/HD-Peaceful-Background.jpg">
<p>Sed augue metus, iaculis non congue a, convallis ut sem. Etiam pulvinar est lorem, non fringilla velit aliquet sit amet. Cras vel eleifend nisl. Suspendisse vitae elit efficitur orci lacinia porta. Aliquam sed quam id velit mattis molestie. Aliquam
id ultricies velit, eu dictum purus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ac porttitor tortor.
</p>
<img id="second" src="https://www.pixelstalk.net/wp-content/uploads/2016/07/HD-Peaceful-Backgrounds.jpg">
<p>Ut vel mi facilisis, mattis diam sit amet, consectetur elit. Nam mollis vestibulum enim, posuere blandit sem. Quisque euismod odio est, vel maximus metus efficitur quis. Morbi ac dignissim massa, in egestas ex. Proin efficitur feugiat libero nec ornare.
Duis vel sapien molestie, efficitur lacus et, ullamcorper tortor. Vestibulum sodales viverra porta. Aenean tincidunt velit nisi, non tempus odio vulputate ut. Praesent accumsan urna et turpis pharetra, vitae consequat diam tempor. Vestibulum sed odio
sem.
</p>
<img id="third" src="https://www.pixelstalk.net/wp-content/uploads/2016/07/HD-Peaceful-Images.jpg">
<p>Aliquam sed quam id velit mattis molestie. Aliquam id ultricies velit, eu dictum purus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ac porttitor tortor.
</p>
<img id="fourth" src="https://www.pixelstalk.net/wp-content/uploads/2016/07/HD-Peaceful-Picture.jpg">
<p>Proin viverra metus enim, vitae egestas tellus lacinia eu. Aenean molestie sollicitudin augue, placerat cursus enim consequat eu. Aenean semper pellentesque augue. Phasellus vel dictum neque. Donec vel imperdiet nisi. Ut sapien turpis, mattis quis lobortis
ut, placerat eget metus. Vestibulum neque ante, lobortis id accumsan a, pellentesque quis nisl. Quisque ac ante ut arcu faucibus molestie sit amet ac dui. Fusce elit nisi, ullamcorper eu eros eget, tempus suscipit purus. Aenean sed nibh urna. Vestibulum
vehicula dapibus ante at viverra. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed purus urna, condimentum sed dictum quis, blandit vel tellus. Sed pretium elit eros, sed congue lectus dictum in. In auctor diam sit amet augue congue
blandit. Vivamus ut enim in mauris venenatis vulputate. Nulla felis tellus, vestibulum at hendrerit auctor, porta a purus. Aenean ac ante vitae turpis rutrum hendrerit eget nec ante. Phasellus bibendum egestas nisi, ac aliquet mi sollicitudin ac.
Sed bibendum quam et mi bibendum ultricies. Pellentesque nec ante viverra, dictum turpis ac, sollicitudin dolor. Vestibulum ut interdum neque. Cras aliquet porta dui, sit amet luctus mauris egestas et. Aliquam quis imperdiet sapien, sollicitudin facilisis diam. Fusce at commodo sapien. Nam at erat nisl. Sed placerat risus vel consequat congue. Nam ultricies ultricies suscipit. Nunc ultrices, dui ut blandit porta, lorem sem dapibus diam, vitae porta tellus nisi ac nibh. Cras pulvinar laoreet dignissim. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae;
</p>
<p> Sed augue metus, iaculis non congue a, convallis ut sem. Etiam pulvinar est lorem, non fringilla velit aliquet sit amet. Cras vel eleifend nisl. Suspendisse vitae elit efficitur orci lacinia porta. Aliquam sed quam id velit mattis molestie. Aliquam id ultricies velit, eu dictum purus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ac porttitor tortor.
</p>
</div>

Positioning style.left for DIV with javascript does not work

I just want to make a DIV jiggle on mouse stop. So I thought I'd set the style.left property using javascript and some timers. To simulate a mouse stop even, I created a timer that is set and cleared as long as the mouse is moving. When the mouse stops, the timer is no longer cleared, and the simulated event "fires." This sets up three more timers. First timer moves the DIV left by 5 pixels. Next timer moves the DIV right by 5 pixels. Final timer moves DIV back to original position.
Sounds easy, and the style.left property of the DIV gets written to the console, which reports the correct values.
But...I never see the DIV move. Why????
The complete code is:
var jLeft = document.getElementById('jiggle').style.left;
function myMoveFunction() {
//Keep clearing and setting the timeout event as long as the mouse is in motion.
//When the mouse stops, the timeout event will fire.
if (typeof touchTimeout == 'undefined') {
touchTimeout = setTimeout(myTimeOut, 50);
} else {
clearTimeout(touchTimeout);
touchTimeout = setTimeout(myTimeOut, 50);
}
//If the mouse is in motion, clear all jiggling events
if (typeof jigLeft !== 'undefined') clearTimeout(jigLeft);
if (typeof jigRight !== 'undefined') clearTimeout(jigRight);
if (typeof jigZero !== 'undefined') clearTimeout(jigZero);
console.clear();
}
function myTimeOut() {
//set up all jiggling events
setTimeout(jigLeft(), 1);
setTimeout(jigRight(), 50);
setTimeout(jigZero(), 99);
}
function jigLeft() {
jLeft = '45px';
console.log('Move Left: ' + jLeft);
}
function jigRight() {
jLeft = '55px';
console.log('Move Right: ' + jLeft);
}
function jigZero() {
jLeft = '50px';
console.log('Move Zero: ' + jLeft);
}
DIV#jiggle {
position: absolute;
left: 50px;
top: 10px;
width: 500px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id='jiggle' onmousemove="myMoveFunction()">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id libero a enim semper bibendum. Suspendisse sodales vulputate posuere. Nulla ac blandit neque, ultricies molestie eros. Donec mauris dolor, rhoncus ac varius sit amet, condimentum sed libero.
Nunc pellentesque quam odio, sit amet vulputate justo blandit sit amet. Sed lorem eros, aliquet at ex quis, cursus gravida urna. Aliquam erat volutpat. Suspendisse rhoncus vulputate nisi non ornare. Proin tincidunt sollicitudin elit, eget aliquam
nisi bibendum at. Duis eget lectus nisi. Praesent nec purus efficitur, pharetra felis sit amet, varius magna. Donec eu justo pretium metus sagittis congue id et lacus. Fusce posuere lacinia nulla a elementum. Nulla consequat mauris orci, ullamcorper
viverra arcu tincidunt sed. Morbi a sem porta est tincidunt semper eu sit amet quam. Integer placerat non risus et elementum. Phasellus eu orci viverra, aliquet est id, condimentum leo. Nunc ac interdum nunc. Morbi at risus nunc. Morbi semper turpis
elit, vel lacinia elit congue id. Maecenas cursus, tellus condimentum pulvinar viverra, ante orci placerat erat, vitae pharetra urna neque quis sem. Nullam non sollicitudin ante, at iaculis sem. Mauris sagittis eros dolor, vitae tempus libero gravida
in. Suspendisse et placerat urna, sed tincidunt nulla. Nam tincidunt pulvinar nisi in condimentum. Sed sem ante, scelerisque eget nulla vitae, elementum mattis turpis. Vestibulum in imperdiet risus. Vestibulum aliquam augue nec tristique pretium.
Nullam vestibulum, felis ut iaculis interdum, ante enim suscipit justo, ac consequat lacus nulla vel turpis. Sed lacinia, leo vel hendrerit aliquet, elit lectus tempor augue, tincidunt condimentum turpis erat eget ipsum. Nam lectus nibh, laoreet sed
accumsan nec, ullamcorper suscipit lectus. Cras faucibus in elit vitae interdum. Morbi vulputate sapien lacus, vel aliquet erat posuere nec. Suspendisse non nibh sapien. Nullam pulvinar diam a aliquam placerat. Donec porttitor commodo nulla, vel egestas
libero facilisis sit amet. Donec eget justo pretium, sagittis ligula in, aliquam orci. Pellentesque ornare purus ut nisi accumsan vehicula. Sed imperdiet dictum odio, in tempor diam rhoncus ut. Mauris vel urna vel turpis cursus facilisis. Suspendisse
eget posuere dolor, eget vulputate massa. Mauris eget ante ac ante accumsan luctus. Curabitur imperdiet condimentum felis, eget faucibus nisl dapibus eu. Curabitur aliquet consectetur dolor, dapibus hendrerit lectus bibendum in. Lorem ipsum dolor
sit amet, consectetur adipiscing elit. Ut ligula nisl, malesuada at tortor at, faucibus maximus dolor. Vivamus condimentum mi at est lobortis, quis pulvinar justo consectetur. Cras eu nunc quis velit placerat consectetur. Quisque dui felis, placerat
id tempor eget, maximus ut lacus. In ante lacus, luctus vel turpis lobortis, dictum dictum massa. Curabitur rutrum dolor ut tincidunt venenatis. Vivamus aliquam ante quam, non cursus enim sollicitudin vitae. Sed rhoncus metus tempor scelerisque interdum.
Pellentesque metus mi, varius ac purus et, euismod commodo purus. Donec eu purus consequat, gravida ipsum quis, efficitur eros. Nulla ornare turpis et nulla consectetur feugiat.
</div>
</body>
</html>
In case you're looking for the fixed code, here it is
HTML
<div id='jiggle' onmousemove="myMoveFunction()">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id libero a enim semper bibendum. Suspendisse sodales vulputate posuere. Nulla ac blandit neque, ultricies molestie eros. Donec mauris dolor, rhoncus ac varius sit amet, condimentum sed libero. Nunc pellentesque quam odio, sit amet vulputate justo blandit sit amet. Sed lorem eros, aliquet at ex quis, cursus gravida urna. Aliquam erat volutpat. Suspendisse rhoncus vulputate nisi non ornare. Proin tincidunt sollicitudin elit, eget aliquam nisi bibendum at. Duis eget lectus nisi. Praesent nec purus efficitur, pharetra felis sit amet, varius magna. Donec eu justo pretium metus sagittis congue id et lacus. Fusce posuere lacinia nulla a elementum. Nulla consequat mauris orci, ullamcorper viverra arcu tincidunt sed. Morbi a sem porta est tincidunt semper eu sit amet quam.
</div>
CSS
DIV#jiggle{
position:absolute;
left:50px;
top:10px;
width:500px;
}
JS
var jLeft = document.getElementById('jiggle').style.left;
function myMoveFunction(){
//Keep clearing and setting the timeout event as long as the mouse is in motion.
//When the mouse stops, the timeout event will fire.
if (typeof touchTimeout == 'undefined') {
touchTimeout = setTimeout(myTimeOut, 50);
} else {
clearTimeout(touchTimeout);
touchTimeout = setTimeout(myTimeOut, 50);
}
//If the mouse is in motion, clear all jiggling events
if (typeof jigLeft !== 'undefined') clearTimeout(jigLeft);
if (typeof jigRight !== 'undefined') clearTimeout(jigRight);
if (typeof jigZero !== 'undefined') clearTimeout(jigZero);
console.clear();
}
function myTimeOut(){
//set up all jiggling events
setTimeout(jigLeft, 1);
setTimeout(jigRight, 50);
setTimeout(jigZero, 99);
}
function jigLeft() {
document.getElementById('jiggle').style.left ='45px';
console.log('Move Left: ' + jLeft);
}
function jigRight() {
document.getElementById('jiggle').style.left = '55px';
console.log('Move Right: ' + jLeft);
}
function jigZero(){
document.getElementById('jiggle').style.left = '50px';
console.log('Move Zero: ' + jLeft);
}
As pointed out by #Quentin, there's a lot of things wrong with your code. This answer fixes most of them.
Here's a fiddle:
https://codepen.io/faisalrashid/pen/dybVvdQ
Problem 1
document.getElementById('jiggle')
This throws an exception. The element does not exist in the DOM at the time you run it.
Problem 2
var jLeft = document.getElementById('jiggle').style.left;
This copies the value. It does not create a reference.
Later, when you assign to jLeft you change only the value of the variable. Not the value of the property.
Problem 3
setTimeout(jigLeft(), 1);
You're calling jigLeft immediately and assigning the return value as the function to run later. It doesn't return a function.
Problem 4
(typeof jigLeft !== 'undefined')
This will never be undefined. It will always be a function.

Load html elements from separate urls in menu list

I have a site with navigation like:
<ul>
<li>
Link 1
</li>
<li>
Link 2
</li>
<li>
Link 3
</li>
<li>
Link 4
</li>
</ul>
When a user clicks on any of the links, the main content from each of the urls will be loaded onto one page, and the page scrolls down to the relevant section. I've tried something like below but it doesn't seem like the best solution. Is there a better way of doing this? Thanks. Should also point out that the code below doesn't work correctly, it loads the content more than once and in a random order.
$( "ul > li > a" ).each(function(index) {
var newhref = $(this).attr('href');
$.get(newhref).done(function (html) {
$(".main-copy").append($(html).find(".main-copy"));
});
});
To begin with I would suggest that each link should be inside it's own -li- like this:
<ul>
<li>
Link 1
</li>
<li>
Link 2
</li>
<li>
Link 3
</li>
<li>
Link 4
</li>
</ul>
As for the JQuery, something like this should do the trick:
$( "ul > li > a" ).click(function(){
$(".main-copy").load($(this).attr('href'));
});
I hope that sets you on the right path
Are these links hard-coded or dynamically generated?
In either case, get all these links into a JavaScript Array:var links=['link1','link2'...]
Since you want to dump all the content by navigating through each of these links, you can loop-through links and append content
for(i=0;i<links.length;i++) {
var link = links[i];
$.ajax(link).done(function(htmlContent){
//set contents to some section or div
});
}
Now the links themselves can be a #href tags with-in the page.
My suggestion would be not to navigate using Jquery on UL -> LI path to get the list of links.
If the load thing is working, are you simply looking at the scrolling thing? Try something like this:
// Creating a dummy namespace, as I don't have content to actually load via ajax.
var myNameSpace = {
"link1": " <p>Proin eget tortor risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque in ipsum id orci porta dapibus. Curabitur aliquet quam id dui posuere blandit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Nulla porttitor accumsan tincidunt. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget tortor risus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus.</p><p>Proin eget tortor risus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Curabitur aliquet quam id dui posuere blandit. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat. Nulla porttitor accumsan tincidunt. Proin eget tortor risus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Donec sollicitudin molestie malesuada. Curabitur aliquet quam id dui posuere blandit.</p><p>Curabitur aliquet quam id dui posuere blandit. Nulla porttitor accumsan tincidunt. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Vivamus suscipit tortor eget felis porttitor volutpat. Cras ultricies ligula sed magna dictum porta. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Curabitur aliquet quam id dui posuere blandit.</p>",
"link2": " <p>Proin eget tortor risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque in ipsum id orci porta dapibus. Curabitur aliquet quam id dui posuere blandit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Nulla porttitor accumsan tincidunt. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget tortor risus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus.</p><p>Proin eget tortor risus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Curabitur aliquet quam id dui posuere blandit. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat. Nulla porttitor accumsan tincidunt. Proin eget tortor risus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Donec sollicitudin molestie malesuada. Curabitur aliquet quam id dui posuere blandit.</p><p>Curabitur aliquet quam id dui posuere blandit. Nulla porttitor accumsan tincidunt. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Vivamus suscipit tortor eget felis porttitor volutpat. Cras ultricies ligula sed magna dictum porta. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Curabitur aliquet quam id dui posuere blandit.</p>",
"link3": " <p>Proin eget tortor risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque in ipsum id orci porta dapibus. Curabitur aliquet quam id dui posuere blandit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Nulla porttitor accumsan tincidunt. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget tortor risus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus.</p><p>Proin eget tortor risus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Curabitur aliquet quam id dui posuere blandit. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat. Nulla porttitor accumsan tincidunt. Proin eget tortor risus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Donec sollicitudin molestie malesuada. Curabitur aliquet quam id dui posuere blandit.</p><p>Curabitur aliquet quam id dui posuere blandit. Nulla porttitor accumsan tincidunt. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Vivamus suscipit tortor eget felis porttitor volutpat. Cras ultricies ligula sed magna dictum porta. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Curabitur aliquet quam id dui posuere blandit.</p>",
"link4": " <p>Proin eget tortor risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque in ipsum id orci porta dapibus. Curabitur aliquet quam id dui posuere blandit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Nulla porttitor accumsan tincidunt. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget tortor risus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus.</p><p>Proin eget tortor risus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Curabitur aliquet quam id dui posuere blandit. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat. Nulla porttitor accumsan tincidunt. Proin eget tortor risus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Donec sollicitudin molestie malesuada. Curabitur aliquet quam id dui posuere blandit.</p><p>Curabitur aliquet quam id dui posuere blandit. Nulla porttitor accumsan tincidunt. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Vivamus suscipit tortor eget felis porttitor volutpat. Cras ultricies ligula sed magna dictum porta. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Curabitur aliquet quam id dui posuere blandit.</p>"
};
// Take each of the navigation elements, and use them to create the content sections
$("nav a").each(function() {
/***
* This would be where you'd first want to load
* your HTML content, rather than using the namespace.
***/
// Get the actual text of the anchor, we'll use that later
var target = $(this).attr("href").substring(1);
// create the section tag...
var myTargetEl = document.createElement("section");
// set the id for the link to use as a target
$(myTargetEl).attr("id", target).append("<h2>" + target + "</h2>").append(myNameSpace[target]);
// Add the section we've created to the content pane
$(".content-pane").append(myTargetEl);
// AND CHANGE THE ACTUAL LINK -- I don't want to reload
// this content every time!
$(this).attr("href", "#" + target);
});
$("nav a").click(function() {
var target = $($(this).attr("href"));
if (target.length) {
event.preventDefault();
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 1000);
}
})
nav {
position: fixed;
left: 10px;
top: 10px;
float: left;
width: 100px;
background-color: #ccc;
}
.content-pane {
position: relative;
left: 120px;
width: 400px;
height: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
Content 1
Content 2
Content 3
Content 4
</nav>
<div class="content-pane">
</div>
As far as the load thing goes, simply load each link into its own section tag. In fact, use the link list to create the section blocks, so that if you add more navigation elements, they'll load dynamically.
Modified the code so that there are no sections being inserted manually, they're created by the link tags themselves. As to how you'd load them, you seem to be doing that all right -- all you're missing is the changing the link's HREF to point to the appropriate section each time.

dynamically change value on resize and window scroll

I have a fixed header function like below. I would like to change dynamically "100" value while window resizing.
I was trying to wrap everything in sth like "if (screen.width >= 1200)" or "jQuery(window).on('resize', function ()" but this kind of stuff is working only with page refresh.
jQuery(document).ready(function($) {
var $window = $(window),
$stickyEl = $('.tabsmenu > ul'),
elTop = $stickyEl.offset().top - 100;
$window.scroll(function() {
if ($window.scrollTop() < 900) {
$stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
} else {
$stickyEl.removeClass('sticky');
}
});
});
Any tips?
This may not be perfect but it's what I think what you want to do and the way I would do it. This just gets the scroll value and then does some math to calculate how much it needs to change. I have added a bunch of content to let it scroll.
window.onload = function() {
$("#everything").scroll(function() {
var startAt = 40; //How many pixles scrolled to start effect, 0 would match link
if ($("#everything").scrollTop() >= startAt) {
var scroll = $("#everything").scrollTop(),
total = 0, // go to this value
distance = 40, //distance to shrink
value = (scroll < distance) ? total : total + (distance - (scroll - startAt));
$("#head").css("height", value); //change #head to what ever you want to shrink
} else {
$("#head").css("background-color", value);
}
});
}
html,
body {
overflow: hidden;
/* Disables regular scrolling */
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
#everything {
overflow: scroll;
/* enables content to scroll */
position: relative;
width: 100%;
height: 100%;
padding-top: 40px;
}
#head {
width: 100%;
height: 40px;
background-color: red;
position: fixed;
top: 0px;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div id="everything">
<div id="head">header</div>
<span>
Text Following text is so the page can scroll: <br/>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer porta velit eu turpis imperdiet congue. Morbi nec mi ipsum. Nam eu nunc in lorem sagittis feugiat a quis nisl. Donec suscipit leo quis magna egestas, id convallis leo gravida. Curabitur finibus lectus ut metus feugiat, eu tincidunt eros tempor. Fusce facilisis nunc vulputate, posuere velit nec, ultrices diam. Vestibulum aliquam velit in lectus imperdiet, vitae condimentum lectus finibus. Aliquam ac arcu eget velit molestie rhoncus. Etiam rhoncus, tellus nec lacinia porta, diam lorem ultrices sem, et dignissim ipsum augue non augue. Suspendisse tincidunt felis sit amet orci accumsan, at ornare tellus viverra. Nam viverra nulla in urna elementum ornare.Sed interdum nisi libero, id porta turpis consectetur vitae. Curabitur nunc ex, interdum eget hendrerit maximus, faucibus non est. Etiam scelerisque condimentum eleifend. Integer ac ligula eget magna porta tristique at eu neque. Sed venenatis ipsum non metus sodales finibus. Suspendisse nec nunc lobortis ligula venenatis tristique. Suspendisse aliquam leo elit, et pretium ipsum tempor sed. Maecenas tincidunt dictum leo sit amet accumsan. Nullam eu viverra nulla. Aenean vehicula tellus a mauris malesuada interdum. Sed libero lacus, consectetur at condimentum vel, egestas vitae nisl.Mauris facilisis tincidunt magna, at gravida elit. Cras molestie eros sed tincidunt ultricies. Pellentesque eleifend egestas orci, sit amet condimentum nisl semper eleifend. Sed ipsum elit, aliquet nec lacinia a, maximus eu dolor. Quisque finibus efficitur odio gravida convallis. Vivamus nec velit in est ornare luctus at a risus. In hac habitasse platea dictumst. Proin condimentum eget est non posuere. Vivamus ante quam, bibendum in tincidunt ut, egestas sed mauris. Nunc non interdum nibh, nec ornare tellus. In interdum elit nisi, a interdum est tempor id. Cras a elit ut purus ornare mollis sit amet ut est. Cras ut ex sed neque lacinia accumsan quis aliquet turpis. Quisque nisl nunc, pretium sed lectus pretium, lacinia ornare magna. Curabitur sit amet felis turpis. Morbi nisi mi, mattis quis tempor ut, accumsan nec ex.
</span>
</div>
</body>
</html>

jquery - trimming image to remove div

i am trying through jquery to remove a div completely when there is no child element within it. The variable I am using is an image. I can't seem to select the variable as an image, i only know how to do this through text. Could someone please help me and resolve this issue, so it detects that there is a img contained within the div and displays it and when there isn't an image it doesn't display it.
I have uploaded it through jsfiddle:http://jsfiddle.net/cLkFD/
<div class="content-container"><!--content-container-->
<h3>title</h3>
<div class="picture"><!--picture-->
<img src="images/buddha.jpg" width="981" height="324" alt=""/>
</div><!--/picture-->
<div class="content"><!--content-->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas et cursus neque, sit amet blandit tellus. Cras leo mauris, laoreet quis consequat et, pharetra mattis risus. Duis tortor lorem, ultrices egestas arcu sed, pretium egestas est. Morbi condimentum sem quis tortor placerat iaculis. Ut nisl augue, rutrum sed sem et, blandit hendrerit nibh. Donec et rhoncus odio, id tempor enim. Praesent ultricies justo vulputate dui gravida fermentum. Pellentesque id aliquet leo. Quisque vulputate, dolor vel rutrum accumsan, turpis odio faucibus sem, vel malesuada eros turpis ac magna. Nullam fermentum vehicula odio, ut ornare justo varius nec. Morbi lectus leo, porttitor nec elementum at, suscipit aliquam nunc. Ut gravida a sem ut imperdiet. Duis et turpis eget magna lobortis accumsan. In ac tincidunt nibh, quis pulvinar risus.
</p>
<button class="btn btn-1 btn-1a">Read More</button>
</div><!--content-->
</div><!--content-container-->
(function($) {
$.fn.equalHeights = function(minHeight, maxHeight) {
tallest = (minHeight) ? minHeight : 0;
this.each(function() {
if($(this).height() > tallest) {
tallest = $(this).height();
}
});
if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
return this.each(function() {
$(this).height(tallest).css("overflow","hidden");
});
}
})(jQuery);
You can check to see whether any image inside your div or not using length:
$(function () {
$('.picture').each(function () {
if ($(this).find('img').length) {
$(this).hide();
}
});
});
http://jsfiddle.net/9VBJP/
The above fiddle should work
$('.picture').each(function(){
var imageElem = $(this).find('img');
if(imageElem.length == 0) {
$(this).hide();
}
});

Categories

Resources