jQuery not doing anything - javascript

I have this jQuery which should 'slide in' a header after scrolling on the page, but nothing happens. At the 3rd line, my code editor gives me a !read only alert, perhaps theres a problem with the syntax?
I'm using beaver builder which calls jQuery automatically.
$( document ).ready(function() {
$(window).scroll(function(){
scroll = $(window).scrollTop();
if (scroll > 450){
$('#jQuery-mob').slideDown();
}
if (scroll < 450){
$('#jQuery-mob').slideUp();
}
});
});
$( document ).ready(function() {
$(window).scroll(function(){
scroll = $(window).scrollTop();
if (scroll > 700){
$('#why-jquery').slideDown();
}
if (scroll < 700){
$('#why-jquery').slideUp();
}
});
});
both #jquery-mob and #why-jquery are set to display:none
css:
#why-jquery {
position: fixed;
top:0;
z-index: 99;
width: 100%;
height: 100px;
display: none;
}
#jQuery-mob {
position: fixed;
top:0;
z-index: 99;
width: 100%;
height: 100px;
padding: 0 !important;
display: none;
}

I'm using beaver builder which calls jQuery automatically.
I think you mean to say:
I'm using wordpress which calls jQuery automatically.
For wordpress sites you must, by default, use jQuery instead of $. You can either replace all, or only use jQuery in the .ready "wrapper" and pass the $ into the .ready function.
Example of both:
jQuery( document ).ready(function() {
jQuery(window).scroll(function(){
scroll = jQuery(window).scrollTop();
if (scroll > 450){
jQuery('#jQuery-mob').slideDown();
}
if (scroll < 450){
jQuery('#jQuery-mob').slideUp();
}
});
});
jQuery(document).ready(function( $ ) {
$(window).scroll(function(){
scroll = $(window).scrollTop();
if (scroll > 700){
$('#why-jquery').slideDown();
}
if (scroll < 700){
$('#why-jquery').slideUp();
}
});
});
Be aware I did not check your code, but I did see you're using scroll without declaring it with var. This means scroll will be a global variable. Both functions setting/using it could cause interference with each other, as well as overwriting window.scroll function. You may want to use var scroll= etc. and also better use another variable name.

scroll is a window-level function, so in a browser context acts as a reserved word:
console.log(scroll)
You're trying to overwrite it with a variable named "scroll", which is what causes the "!read only" error you're seeing.
Use a different variable name (and declare it using 'var'.)

This code has logical issue
if (scroll < 450 && scroll < 800){
When scroll is smaller than 450, it is smaller than 800 as well, so why did you include the second comparison?
The same story on this line:
if (scroll < 700 && scroll < 1000){

Related

Removing An Appended jQuery Div When Window Resizes - jQuery

I've appended some divs onto a nav with jQuery. These are set so they append if the window is bigger than 980px.
I would like these appended divs to be removed if the window is less than 980px. The jQuery I'm using in the example works, but only if the window is this size when loaded. When I re-size the window the appended divs don't get removed or added which is what I need.
I have a codepen here: http://codepen.io/emilychews/pen/jBGGBB
The code is:
jQuery
if ($(window).width() >= 980) {
$('.box').append('<div id="newbox">appended with jQuery</div>');
}
if ($(window).width() <= 979) {
$('#newbox').remove();
}
CSS
.box{
position: relative;
left: 50px;
top: 50px;
height: 30px;
width: 100px;
background: blue;
line-height: 30px;
text-align: center;
color: white;
}
#newbox {
margin-top: 20px;
width: 100px;
height: 100px;
background: red;}
HTML
<div class="box">Test</div>
Any help would be wonderful.
Emily
I've updated your codepen to show how you can accomplish this:
Code Pen Here: http://codepen.io/anon/pen/ZeXrar
// Logic inside of function
function addRemoveDiv() {
// Window Width pointer
var wW = $(window).width();
// If window width is greater than or equal to 980 and div not created.
if (wW >= 980 && !$('#newbox').length) {
$('.box').append('<div id="newbox">appended with jQuery</div>');
// else if window is less than 980 and #newbox has been created.
} else if (wW < 980 && $('#newbox').length) {
$('#newbox').remove();
}
}
// Initial function call.
addRemoveDiv();
// On resize, call the function again
$(window).on('resize', function() {
addRemoveDiv();
})
Also, I would recommend looking into debouncing the function call on resize so it's not called over and over and over again as the window resizes. Reference for that here:
https://davidwalsh.name/javascript-debounce-function
Also, libraries like Underscore and LoDash have debounce functions available when sourced:
http://underscorejs.org/
https://lodash.com/
You should use event listeners.
$(document).ready(function() {
function checkMyDiv(calledByResize) {
if($(window).width() >= 980 && $('#newbox').length < 1) { // "$('#newbox').length < 1" will prevent to add lots of div#newbox elements
$('.box').append('<div id="newbox">appended with jQuery</div>');
} else if (calledByResize === true && $('#newbox').length > 0) {
$('#newbox').remove();
}
}
$(window).resize(function() {
checkMyDiv(true);
});
checkMyDiv(false);
});
You may also want to use css rules, like display:none|block; instead of removing or appending div#newbox element everytime the window resizes.
You're almost there, you just need the resize event, and for it to be applied after the ready event:
(function($) {
$(function() {
$(window).on('resize', function() {
if ($(window).width() >= 980) {
$('.box').append('<div id="newbox">appended with jQuery</div>');
}
if ($(window).width() <= 979) {
$('#newbox').remove();
}
}).trigger('resize');
});
})(jQuery);
Although, it should be noted this will actually append an additional copy of your newbox on every single resize event, which I'll assume you don't want. So, we'll sort out that problem.
We can also do a few simple optimisations here to make the code slightly more efficient, such as storing our element selectors and window width in variables:
(function($) {
$(function() {
var $window = $(window),
newBox = $('<div id="newbox">appended with jQuery</div>'),
box = $('.box');
$window.on('resize', function() {
var windowWidth = $window.width();
if (windowWidth >= 980) {
if(!$.contains(document, newBox[0])) {
box.append(newBox);
}
} else if (windowWidth <= 979) {
if($.contains(document, newBox[0])) {
newBox.remove();
}
}
}).trigger('resize');
});
})(jQuery);
I think you need to add an event listener on the window object, listening for the .resize() event:
https://api.jquery.com/resize/
Then in the callback function you should be able to check whether the new size is below your threshold, so you can remove the div in that case.
$(window).resize(function () {
// Check window width here, and remove div if necessary
})

make div scoll untill it reaches top of page then fixed

let's get straight to the point:
My code looks like the following:
<div id="keep_up">
<div id="thread_menu">
<div id="new_thread">
</div>
</div>
</div>
And my css:
#keep_up {
position: fixed;
width: 13%;
}
#thread_menu{
height: 80vh;
width: 100%;
float: left;
position: relative;
}
Now i use this for a forum. and this is basically to show the active and new threads on the side of the screen.
However. When watching a thread, the header disappears (Wich makes sense because we are scrolling down).
but i want the thread menu to stay on my side (So that it is always visible). In this case that is happening because my keep_up div has position: fixed. But i only see half of the thread menu becuase it is too long and won't scroll up.
My question:
I want the thread menu to scroll up, untill it reaches the top of my window. From then on i want it to stay there.
How do i do this?
I saw a few examples but none of them worked for me.
EDIT: Code i tried:
<script src="jquery.min.js">
$(window).scroll(function () {
var margin = null;
$(window).on("scroll", function () {
var scrollHeight = $(document).height(),
scrollTop = $(window).scrollTop(),
offsetBottom = 110, // Offset depending on the height of the footer
offsetTop = 100, // Offset depending on the height of the header
positionTop = $(".keep_up").offset().top,
affix;
if (margin != null && (scrollTop + margin <= positionTop)) {
// The sidebar has reached the bottom and is still on the bottom
affix = false;
} else if (positionTop + $(".keep_up").height() >= scrollHeight - offsetBottom) {
// The sidebar has reached the bottom
affix = 'bottom';
} else if (scrollTop <= offsetTop) {
// The sidebar has reached the top
affix = 'top';
} else {
// The sidebar is midway
affix = false;
}
// If the sidebar hasnot changed his state, return;
if ($(".keep_up").hasClass('at' + (affix ? '-' + affix : ''))) return;
if (affix == 'bottom') {
margin = positionTop - scrollTop;
} else {
margin = null;
}
// If the related class is added to the div
$(".keep_up").removeClass('at at-top at-bottom').addClass('at' + (affix ? '-' + affix : ''))
});
});
</script>
And the CSS:
.keep_up{
/*position: fixed;*/
width: 13%;
}
.keep_up.at {
top: 1px;
position: fixed;
}
.keep_up.at-top{
}
.keep_up.at-bottom {
top: 438px;
position: absolute;
}
modify this on HTML:
<div id="prevent"></div>
<div id="keep_up" data-spy="affix" data-offset-top="200">
Add this CSS:
.affix{position: fixed !important; top:0px; z-index:999;}
.affixpatch{margin-top:100px !important;}
this will fix the div when you scroll down 200px. Change data-offset-top value to reach it on different break point.
.affixpatch is a class that will be loaded with next jquery function. it prevents to hide content behind top fixed div. Change margin-top to another value if this don't solves the "hide content" problem that always generate affixing divs.
<script>
$(function() {
//caches a jQuery object containing the header element
var header = $(".affix");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 200) {
$('#prevent').addClass("affixpatch");
} else {
$('#prevent').removeClass("affixpatch");
}
});
});
</script>
Hope it helps. If not, you may have some class that rewrite or impede the correct function of this affix.
I've tested this hundreds of times, usually to fix navbars.
SCROLL:
Using overflow to scroll content:
#keep_up{
max-height:400px;
width: auto;
overflow:auto;}
This will scroll the content inside #keep_up div (or use it in another one)
NOTE: you must declare a fixed max height for this div. Set max-width only if you need.
You can use %, em, rem... no need to be px for fix the max witdth. (to get a responsive effect, use responsive measurements)
If I understand your scenario correctly, the way to do this might be to use jQuery (or native JS, but you've tagged jQuery so I'm assuming that's in play).
There's a plugin that handles this kind of thing: http://leafo.net/sticky-kit/
I'd suggest you look at the plugin source code to see how it works - an event handler function on $(window).scroll() which then toggles classes on your #thread_menu to fix it in place. To keep your code lightweight, you probably don't need everything the plugin provides.

A cleaner way for a fixed div at bottom of the window but stays above the footer and triggers on page width

I've created a sticky bar to stay at the bottom of the window. As the user scrolls down to the bottom of the page the same bar will stay fixed until the footer shows, then removes its fixed position, temporarily, to stay above the footer until the user scrolls back up and it remains fixed again.
I only want to happen when the page is wider than 680px. Anything under that will keep the sticky bar in a default position (CSS: position:inherit).
This is the website: http://ttd.firefly-digital.co.uk
It works as expected. However, when I test on Chrome in Mac it triggers my CPU fan which suggests this not very efficient and with my limited JavaScript skills, wondered if there is a cleaner way to achieve this is?
This is the current js code:
$(window).scroll(function(event) {
var scroll = $(this).scrollTop();
var docHeight = $(document).height();
var windowHeight = $(window).height();
var footerHeight = $('.footer').height();
if(docHeight - (windowHeight + scroll) < footerHeight) {
$('.contact-bar').css({
bottom: footerHeight - (docHeight - (windowHeight + scroll))
});
} else {
$('.contact-bar').css({
bottom: 0
});
}
});
var windowWidth = $(window).width();
$(window).resize(function() {
windowWidth = $(window).width();
if(windowWidth > 680) {
$('.contact-bar').css({
position: "fixed"
});
} else {
$('.contact-bar').css({
position: "inherit"
});
}
});
CSS code
.contact-bar {
background: $contact-bar;
width: 100%;
height: 40px;
text-align: center;
position: fixed;
bottom: 0;
z-index: 10;
}
You can do it in reverse. Make it so that the bar, without position fixed, is above the footer without any JavaScript (incl. media queries). Than add a fixed class with position:fixed and bottom:0 that will be added accordingly. Like so:
.contact-bar.fixed { position:fixed; bottom:0; }
The jquery code that will trigger this, is as follows:
$(window).scroll(function (event) {
var windowTop = $(this).scrollTop();
if (windowTop >= $(".footer").offset().top) {
$(".contact-bar").addClass("fixed");
} else {
$(".contact-bar").removeClass("fixed");
}
});
Then add a few lines that the above code will only fire if the window width is > 680, either with jquery or pure javascript. For example with:
if ($(window).width() < 960) { // above function }
Do note I have not tested this, so please comment if it doesn't work. Credit: Preventing element from displaying on top of footer when using position:fixed
You better use classes to target your elements, at least to prevent jQuery from traversing the whole DOM using selectors appropriately which is good in performance.

Making a nav bar revert to normal after scrolling to top of page

So i'm trying to learn javascript and jQuery. I was coding a project website and wanted to make the nav smaller and transparent as they scroll around the page. i wrote this and it works fine `
$(document).scroll(function(){
$('.nav').css({"opacity": "0.85", "height": "55px"});
$('.nav-container').css({"margin-top": "-13px", "font-size": "1.4em"})
});
`
But i want it to revert back to normal when they scroll all the way to the top. There doesn't seem to be a jQuery event for this.
I'd personally suggest:
$(document).scroll(function () {
// select the relevant elements:
$('#nav, .nav-container')[
// if the window is at the 'top', we use the 'removeClass' method,
// otherwise we use 'addClass':
$(window).scrollTop() == 0 ? 'removeClass' : 'addClass'
// and pass the 'scrolled' class-name to the method:
]('scrolled');
});
With the CSS:
.nav.scrolled {
opacity: 0.85;
height: 55px;
}
.nav-container.scrolled {
margin-top: -13px;
font-size: 1.4em;
}
JS Fiddle demo.
This also uses corrected (valid HTML).
References:
addClass().
removeClass().
scroll().
I have updated your jsfiddle here
I just changed your .scroll() function:
$(document).scroll(function () {
var scroll = $(this).scrollTop();
if(scroll > 0){
$('.nav').addClass('scrolled');
$('.nav-container').addClass('scrolled');
} else if(scroll == 0){
$('.nav').removeClass('scrolled');
$('.nav-container').removeClass('scrolled');
}
});
and added this css:
.nav.scrolled {
opacity:0.85;
height:55px;
}
.nav-container.scrolled {
margin-top:-13px;
font-size:1.4em;
}

Submenu position issue

I have scrolling a menu on my website http://www.whirlware.biz, it works fine at all but have a bug in submenus (company and services), submenu appears strange way when page is scrolled. I think I need fixed position for submenu, but when I try to make it I had awful results.
My code: (or you can inspect my website)
stickymenu.js
$( document ).ready(function() {
var left = document.getElementById("zt-mainmenu");
stop = (left.offsetTop - 60);
window.onscroll = function (e) {
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
if (scrollTop >= stop) {
left.className = 'fixed_m';
} else {
left.className = '';
}
}
});
I tried to add this css but there was no result that I expected:
div.submenu-wrap {
position:fixed !important;
top:0px !important;
left:0px !important;
}
I can`t provide whole css code because style file is big, but if you expect site I think you can find right answer.
Can somebody help me with this? Thanks.
You have a top property that the js plugin is inserting. Either edit the plugin to remove the top property inline, or use this bit of CSS on an existing selector you have:
div.menusys_mega .menusub_mega {
position: absolute;
opacity: 0;
top: inherit !important;
}
It's not ideal because of the !important, but at least you will see what happens when you cancel out the top property.

Categories

Resources