I'm a beginner programmer and I'm trying to create this effect that when I scroll past a specific element in the HTML, The colors of the buttons in my navbar change colors. I thought the correct way of doing this was jQuery. I'm having problems getting the position of the elements in the page. I have tried with the position() and offset() methods. But neither seem to work.
I want to get the vertical positions of the elements with the IDs "info" and "security". I have these methods aren't very reliable in certain cases, but I can't find an alternative.
This is the code I have so far:
$(window).on('load', function(){
window.loaded = true;
console.log("LOADED");
});
$( window ).scroll(function() {
if (window.loaded == true){
var scrollTop = $(window).scrollTop();
var infopos = $( "#info" );
var secpos = $("#security");
if (scrollTop >= 0 && scrollTop < infopos-25) {
$( "#navgeneral" ).addClass("active");
$( "#navinfo" ).removeClass("active");
$( "#navsecurity" ).removeClass("active");
}
else if (scrollTop >= infopos && scrollTop < secpos){
$( "#navgeneral" ).removeClass("active");
$( "#navinfo" ).addClass("active");
$( "#navsecurity" ).removeClass("active");
}
}
});`
Thank you for the advice in advance!!
Here you go.
//Declare these first
const infopos = $( "#info" ).scrollTop();
const secpos = $("#security").scrollTop();
$(window).on('load', function(){
window.loaded = true;
console.log("LOADED");
});
$( window ).scroll(function() {
if (window.loaded === true){
let scrollTop = $(window).scrollTop();
if (scrollTop < infopos-25) { //scrollTop >= 0 will always be true so skip it
$( "#navgeneral" ).addClass("active");
$( "#navinfo" ).removeClass("active");
$( "#navsecurity" ).removeClass("active");
}
else if (scrollTop >= infopos && scrollTop < secpos){
$( "#navgeneral" ).removeClass("active");
$( "#navinfo" ).addClass("active");
$( "#navsecurity" ).removeClass("active");
}
}
});`
First get a good understanding of how variables work and please try to use let instead of var most of the time while declaring variables. This will prevent accidentally overwriting global variables.
The objective mentioned is to let NAV bar change based on the position that you scrolled to.
First you need to get your target ID scroll position.Use code below to get every archor element ID:
$('#testB').position().top
(In jQuery, position will return you the left and top value, here we use top only.)
Second, get the current scroll position.Use code below:
currentHeight = $(window).scrollTop();
Third, write related jQuery code to change NAV elements.Sample JS as below:
Here we have 5 DIV (#testA to E) and 4 nav buttons (#test1 to 4)
$(window).scroll(function () {
var currentHeight = $(window).scrollTop();
if (currentHeight <= $('#testB').position().top) {
$("#test1").addClass('active-blue');
$("#test2").removeClass('active-blue');
$("#test3").removeClass('active-blue');
$("#test4").removeClass('active-blue');
} else if (currentHeight <= $('#testC').position().top) {
$("#test1").removeClass('active-blue');
$("#test2").addClass('active-blue');
$("#test3").removeClass('active-blue');
$("#test4").removeClass('active-blue');
} else if (currentHeight <= $('#testD').position().top) {
$("#test1").removeClass('active-blue');
$("#test2").removeClass('active-blue');
$("#test3").addClass('active-blue');
$("#test4").removeClass('active-blue');
} else {
$("#test1").removeClass('active-blue');
$("#test2").removeClass('active-blue');
$("#test3").removeClass('active-blue');
$("#test4").addClass('active-blue');
}
});
Related
I just write a script to auto positioning an element on my page.
$(document).ready(function(){
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll < 180) {
$(".header-bottom").removeClass("scroll-menu");
if ($(window).width() > 991) {
$(".header_user_top").css("position", "absolute");
$(".header_user_top").css("top", "initial");
$(".header_user_top").css("right", "60px");
$(".header_user_top").css("z-index", "1");
}
} else {
$(".header-bottom").addClass("scroll-menu");
if ($(window).width() > 991) {
var rightContainer = ($(window).width() - ($('#header div.header-bottom div.container').offset().left + $('#header div.header-bottom div.container').outerWidth()));
$(".header_user_top").css("position", "fixed");
$(".header_user_top").css("top", "-22px");
$(".header_user_top").css("right", rightContainer+60+"px");
$(".header_user_top").css("z-index", "99");
}
}
});
});
It's working but if I resize browser window the script doesn't reload.
If I refresh the page it's working.
I have add window.onresize = function(){ location.reload(); }to my script to fix this problem but I'm looking for a better solution.
Any idea?
Use on function to call multiple event:
$(window).on("load resize scroll",function(e){
// do something
}
Call function which is handling size on windows.resize also
function handleSize(){
// You code to handle size
}
window.resize=handleSize();
I'm creating a sticky nav on scroll for a clients website and have got it working. However, because the div above it has a variable height based on the height of the browser window minus the nav for a carousel height: calc(100vh - 100px); it's breaking when the browser window is resized. So can someone help me to add a resize event onto the below code, so that it updates the height of the window on resizing the browser?
var yourNavigation = $(".home-navbar");
stickyDiv = "sticky";
yourHeader = $('.home-carousel').height();
$(window).scroll(function() {
if( $(this).scrollTop() > yourHeader ) {
yourNavigation.addClass(stickyDiv);
$( "#sticky" ).addClass( "sticky__padding" );
} else {
yourNavigation.removeClass(stickyDiv);
$( "#sticky" ).removeClass( "sticky__padding" );
}
});
I think you just want to make the scrollTop check into a function and call it on load, scroll, and resize If so, you can use either pure JS or jQuery to accomplish this:
function headerStuff() {
var yourNavigation = $(".home-navbar");
var stickyDiv = "sticky";
var yourHeader = $('.home-carousel').height();
if( $(this).scrollTop() > yourHeader ) {
yourNavigation.addClass(stickyDiv);
$( "#sticky" ).addClass( "sticky__padding" );
} else {
yourNavigation.removeClass(stickyDiv);
$( "#sticky" ).removeClass( "sticky__padding" );
}
};
window.addEventListener("load", headerStuff);
window.addEventListener("resize", headerStuff);
window.addEventListener("scroll", headerStuff);
Everyone i have two div id like
I have an in and i am getting its content onscroll using jquery.
now i want onscroll pause the video in "myplayer" and it should play from same time in "getMyPlayer"
Thanks in advance.
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
/* alert(scroll);*/
if(scroll > 600)
{
$('#getMyPlayer').css('display','block');
}
else
{
$( '#myplayer' ).clone().appendTo( '#getMyPlayer' );
$('#getMyPlayer').css('display','none');
}
});
<div id="myplayer">
<iframe width="500" height="500" src="//www.ytapi.com/embed/<?php echo $yt->id ?>?autoplay=1" frameborder="0" allowfullscreen></iframe>
</div>
<div id="getMyPlayer"></div>
All you have to do is add iframe to the selector before .clone().
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
/* alert(scroll);*/
if(scroll > 600)
{
$('#getMyPlayer').css('display','block');
}
else
{
$( '#myplayer iframe' ).clone().appendTo( '#getMyPlayer' ); // this line is different
$('#getMyPlayer').css('display','none');
}
});
Be careful though because every time the scroll position is updated it will run this code. I would recommend adding an if statement to check if it's already been copied before cloning it.
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
/* alert(scroll);*/
if(scroll > 600)
{
$('#getMyPlayer').css('display','block');
}
else
{
if ($( '#getMyPlayer iframe' ).length === 0) {
$( '#myplayer iframe' ).clone().appendTo( '#getMyPlayer' );
$('#getMyPlayer').css('display','none');
}
}
});
I'm extremely new to JavaScript so I apologize in advance. I'm trying to create a one page html document for a school project using a list of links for navigation that change when the anchor is scrolled to. I've tried various different methods found on Jfiddle and through stackoverflow. This is the method I am trying now: http://jsfiddle.net/m2zQE/
var topRange = 200, // measure from the top of the viewport to X pixels down
edgeMargin = 20, // margin above the top or margin from the end of the page
animationTime = 1200, // time in milliseconds
contentTop = [];
$(document).ready(function () {
// Stop animated scroll if the user does something
$('html,body').bind('scroll mousedown DOMMouseScroll mousewheel keyup', function (e) {
if (e.which > 0 || e.type == 'mousedown' || e.type == 'mousewheel') {
$('html,body').stop();
}
});
// Set up content an array of locations
$('#nav').find('a').each(function () {
contentTop.push($($(this).attr('href')).offset().top);
});
// Animate menu scroll to content
$('#nav').find('a').click(function () {
var sel = this,
newTop = Math.min(contentTop[$('#nav a').index($(this))], $(document).height() - $(window).height()); // get content top or top position if at the document bottom
$('html,body').stop().animate({
'scrollTop': newTop
}, animationTime, function () {
window.location.hash = $(sel).attr('href');
});
return false;
});
// adjust side menu
$(window).scroll(function () {
var winTop = $(window).scrollTop(),
bodyHt = $(document).height(),
vpHt = $(window).height() + edgeMargin; // viewport height + margin
$.each(contentTop, function (i, loc) {
if ((loc > winTop - edgeMargin && (loc < winTop + topRange || (winTop + vpHt) >= bodyHt))) {
$('#nav li')
.removeClass('selected')
.eq(i).addClass('selected');
}
});
});
});
I'm still not having any luck. I've already searched to see if I could debug the problem and have tried changing the order of the code as well as the order of calling jquery.
Here is a link to the site: https://googledrive.com/host/0BwvPQbnPrz_LMlZDeGlFY2Yydmc/index.html
I used html5boilerplate as a starting point.Thank you in advance.
Don't have much time to look into your code, but when I input the line
Math.min(contentTop[$('#nav a').index($(this))], $(document).height() - $(window).height())
into the console of developer tools, it return NaN.
So I guess the problem is you don't have your scrollTop correctly set.
I suggest you give each element an id and try:
$('html, body').animate({
scrollTop: $("#elementID").offset().top
}, 2000);
or if you insist not giving id,
$('html, body').animate({
scrollTop: $("#container-fulid:nth-child(2)").offset().top
}, 2000);
but notice that this is not working on all browser as the nth-child selector is a CSS3 selector.
Or, if you know how to correctly use other's work, you may try to use bootstrap 3.0, where there is already a function named scrollspy included, which do exactly the thing you are doing.
http://getbootstrap.com/javascript/#scrollspy
I have a div with a heading using and i have a Vertical Navigation menu in same div.
To make it responsive i use media query and "Display:none and position:abolute" to Navigation Container.
it works perfectly fine till this step.
NOW what i want is that. when i click this heading the the Navigation menu appears and when i click a Link on the Navigation Menu disappears means the menu itself become"Display:none"
I used .toggle() jquery to achieve this.
when this works perfectly fine.
but problem is that i want that this .toggle() function not to work when the width of window is more then 980px;
<h2 id="heading"><span>Office<span class="blue">Managnment</span></span></h2>
<ul id="list">
<li>P</li>
<li>A</li>
<li>N</li>
<li>L</li>
<li>A</li>
<li>R</li>
<li>P</li>
</ul>
and javascript
$(function () {
$("#heading").click(function () {
$("#list").toggle();
});
$("#list").click(function () {
$("#list").toggle('hide');
});
});
and yes i tried if statement to execute this code only when the width is less then 980px but problem is that it only check for width when the page load. i.e if the window is less then 980 on load. script works fine. but when window is more then 980 on load the script do not work even on resizing it to less then 980px.
i dont understand how to achieve this. mainly problem in choosing the condition for the the if else statement.
load the window and check the width
if it is less then 980px execute the script
if it is more then 980 do not execute the script.
on resize of the window check the new width
if it was more then 980 previously
check if the width increased. if it is increased do nothing(script should not work)
check if the width is now less then 980 . START the script.Script should work now.
if it was less then 980 previosly.
check if the width increased more then 980. if it is increased STOP the script. it should not work now
check if the width is now less then 980 . Do nothing. Script should work now.
IN SHORT turn on the toggle function when width less then 980px. and turn the toggle off and set to show when width is more then 980px.
I figured it out as below. It works, but sometimes when i resize slowly it behave strangely.
var $window = $(window),
ONLOADtoggleEnabled = false,
smallscreenbefore = false;
$window.on('resize', function() {
if (smallscreenbefore == false && $window.width() > 1220) {
} else if( smallscreenbefore == false && $window.width() < 1220) {
$( "#Tablist" ).hide(400);
$( "#heading" ).click(function() {
$( "#Tablist" ).toggle(400);
});
$( "#Tablist" ).click(function() {
$( "#Tablist" ).toggle(400);
});
smallscreenbefore = true;
}
else if(smallscreenbefore == true && $window.width() > 1220 ) {
$( "#heading" ).unbind('click');
$( "#Tablist" ).unbind('click');
$( "#Tablist" ).show(400);
smallscreenbefore = false;
}
else if(smallscreenbefore == true && $window.width() < 1220 ) {
smallscreenbefore = false;
}
});
var $window = $(window);
$window.on('load', function() {
if ($window.width() < 1220) {
$( "#heading" ).click(function() {
$( "#Tablist" ).toggle(400);
});
$( "#Tablist" ).click(function() {
$( "#Tablist" ).toggle(400);
});
smallscreenbefore = true;
}
else if($window.width() > 1220) {
smallscreenbefore = false;
}
});
You can listen for the resize event on the window and then use the width to decide what you want to do. I suppose something like this should work:
var MAX_WIDTH = 980,
$window = $(window),
toggleEnabled = false;
$window.on('resize', function() {
// Check window width and check if toggle isn't already enabled
if ($window.width() < MAX_WIDTH) {
// Check if toggle isn't enabled yet
if (!toggleEnabled) {
// Use on() to add eventListener
$("#heading").on('click', function () {
$("#list").toggle();
});
$("#list").on('click', function () {
$("#list").toggle('hide');
});
toggleEnabled = true;
}
} else if (toggleEnabled) {
// Use off() to remove eventListener
$("#heading").off('click');
$("#list").off('click');
// Show the list
$('#list').show();
toggleEnabled = false;
}
$('#output').text('Width: ' + $window.width() + ', toggleEnabled: ' + toggleEnabled);
});
// You can trigger the resize event at the start to set the initial state of the menu
$window.trigger('resize');
Working version with your list: http://jsfiddle.net/srm6p/3/