jQuery doesn't add class to element - javascript

Simple scroll down -> change navbar sequence using jQuery.
$(document).ready(function () {
'use strict';
var c, currentScrollTop = 0,
navbar = $('nav');
$(window).scroll(function () {
currentScrollTop = a;
if (c > 650) {
navbar.addClass("scrollUp");
console.log("Showing navbar", c, navbar.hasClass("scrollUp"));
} else if (c < 700) {
navbar.removeClass("scrollUp");
}
c = currentScrollTop;
});
}
Console log outputs current scroll and "false" where needed. Class just doesn't add up.
Fyi I'm bad at jQuery and it's the only thing I have in my react app.
scrollUp in CSS adds a background-color transition to nav, making it opaque.
I noticed that sometimes it works, sometimes doesn't and I can't identify the problem. Haven't seen it working for a while now.
Bonus:
$("#toProjects").click(function() {
$('html, body').animate({
scrollTop: $("#projects").offset().top -75
}, scrollSpeed);
return false;
});
This scrollTo function doesn't work as well.
HTML:
<head>
<script language="javascript" src="./jquery.js"></script>
</head>
CSS:
.navbar.scrollUp {
background-color: #000000;
transform: background-color 0s ease 0s;
}

You're setting currentScrollTop to a but a is never defined.
Edit:
I see you have different code on your website than you've posted here.
You're not connecting to your navbar correctly.
Try this instead.
var c, currentScrollTop = 0, navbar = $('#navbar');
$('nav') is looking for elements with the name 'nav', of which, none exist on your page. same as calling $('div') or document.querySelector('div').
$('#navbar') grabs the elements on your page where the id attribute is set to navbar.
This fixes the class not being added part but I think you'll need to work with the css a bit to actually see the affect take place.

The issue was solved by integrating jQuery code directly into ComponentDidMount() function inside React component. That way it re-engages and works fine

Related

drupal js executing another js function without exiting main script?

I got js from FAQ module where nodes are loaded collapsed, with "faq-answer ... collapsable collapsed" and when toggled "faq-answer ... collapsable ("collapsed" disappears).
I suspect that since .collapsed includes 'display: none;' the lazy loading script for images is not triggered.
Therefore, I'm trying to execute that script lazy.js after any faq is toggled but can't make it work.
A) Inside lazy.js i gave it a name (function runblazy($) { and inside faq.js I inserted runblazy(); just after $(this).next('div.faq-dd-hide-answer').toggleClass("collapsed"); but this interrupts the entire script, which prevents the page from properly loading ie. render links etc.
B) I also tried to run it when the class "collapsed" disappeared, but it's only being run once (during page load) and I neither could figure out how to possibly make it work with a while loop
var x = document.getElementsByClassName("faq-answer");
if (x[0].classList.contains("collapsed")) { //do nothing }
else { runblazy(); }
Which would be the better / correct approach, what am I missing?
Here is the js from faq.js :
(function ($) {
Drupal.behaviors.initFaqModule = {
attach: function (context) {
// Hide/show answer for a question.
var faq_hide_qa_accordion = Drupal.settings.faq.faq_hide_qa_accordion;
$('div.faq-dd-hide-answer', context).addClass("collapsible collapsed");
if (!faq_hide_qa_accordion) {
$('div.faq-dd-hide-answer:not(.faq-processed)', context).addClass('faq-processed').hide();
}
$('div.faq-dt-hide-answer:not(.faq-processed)', context).addClass('faq-processed').click(function() {
if (faq_hide_qa_accordion) {
$('div.faq-dt-hide-answer').not($(this)).removeClass('faq-qa-visible');
}
$(this).toggleClass('faq-qa-visible');
$(this).parent().addClass('faq-viewed');
$('div.faq-dd-hide-answer').not($(this).next('div.faq-dd-hide-answer')).addClass("collapsed");
if (!faq_hide_qa_accordion) {
$(this).next('div.faq-dd-hide-answer').slideToggle('fast', function() {
$(this).parent().toggleClass('expanded');
});
}
$(this).next('div.faq-dd-hide-answer').toggleClass("collapsed");
//ADD "runblazy();" HERE?
// Change the fragment, too, for permalink/bookmark.
// To keep the current page from scrolling, refs
// http://stackoverflow.com/questions/1489624/modifying-document-location-hash-without-page-scrolling/1489802#1489802
var hash = $(this).find('a').attr('id');
var fx, node = $('#' + hash);
if (node.length) {
fx = $('<div></div>')
.css({position: 'absolute', visibility: 'hidden', top: $(window).scrollTop() + 'px'})
.attr('id', hash)
.appendTo(document.body);
node.attr('id', '');
}
document.location.hash = hash;
if (node.length) {
fx.remove();
node.attr('id', hash);
}
// Scroll the page if the collapsed FAQ is not visible.
// If we have the toolbar so the title may be hidden by the bar.
var mainScrollTop = Math.max($('html', context).scrollTop(), $('body', context).scrollTop());
// We compute mainScrollTop because the behaviour is different on FF, IE and CR
if (mainScrollTop > $(this).offset().top) {
$('html, body', context).animate({
scrollTop: $(this).offset().top
}, 1);
}
return false;
});
I almost can't believe it, after many hours of trying, I found a very simple fix that worked.
I remembered that I suspected display:none to be the issue for lazy loading not working and read here that this should be avoided, thus changing the .css to use the below instead worked:
.faq .collapsed {
/*display: none;*/
position: absolute !important;
top: -9999px !important;
left: -9999px !important;
}
I would be still interested if there is another way as per question to run the lazy.js after the toggle?

Add class onscroll combined with onepage-scroll.js plug-in

I'm currently using the onepage-scroll.js (https://github.com/peachananr/onepage-scroll) plug-in on my website to scroll through the homepage. When scrolling past the first "slide" I would also like to add a class (sticky) to my header to change some CSS. I've tried the code below, but I can't seem to get it working and I'm kinda in the dark here on how to make this solution work.
var header = $("header");
$("#sliders").scroll(function() {
var scroll = $('#sliders').scrollTop();
console.log(scroll);
if (scroll >= 50) {
header.addClass("sticky");
} else {
header.removeClass("sticky");
}
});
Try to make it on document ready.
Down only my example worked code on onepage-scroll.js
$(document).ready(function(){
$(".main").onepage_scroll({
sectionContainer: ".sectionscroll",
responsiveFallback: 600,
loop: true,
afterMove:function (index){
if ((index == 2)||(index == 3)){
$('#main').addClass('darktheme');
}else{
$('#main').removeClass('darktheme');
}
}
});
//$(".main").moveTo(2);
$(".btn-list-bottom").click(function(){$(".main").moveTo(4)});
});
All you section must have the same class.

On scroll, logo color changes, but scrolling back up it stays the same

Im creating a fixed header where on load, the logo is flat white. On scroll, it changes to the full color logo.
However, when scrolling back to the top, it stays the same colored logo instead of going back to white.
Here's the code (and a pen)
$(function() {
$(window).scroll(function() {
var navlogo = $('.nav-logo-before');
var scroll = $(window).scrollTop();
if (scroll >= 1) {
navlogo.removeClass('.nav-logo-before').addClass('nav-logo-after');
} else {
navlogo.removeClass('.nav-logo-after').addClass('nav-logo-before');
}
});
});
http://codepen.io/bradpaulp/pen/gmXOjG
There's a couple of things here:
1) You start with a .nav-logo-before class but when the logo becomes black you remove that class and then try to get the same element using a class selector that doesn't exist anymore
2) removeClass('.nav-logo-before') is different than removeClass('nev-logo-before), notice the "." in the first selector.
3) You get the element using the $('.selector')in every scroll event, this can be a performance issue, it's better to cache them on page load and then use the element stored in memory
4) It's not a good practice to listen to scroll events as this can be too performance demanding, it's usually better to use the requestAnimationFrame and then check if the scroll position has changed. Using the scroll event it could happen that you scroll up really fast and the scroll event doesn't happen at 0, so your logo won't change. With requestAnimationFrame this can't happen
$(function() {
var navlogo = $('.nav-logo');
var $window = $(window);
var oldScroll = 0;
function loop() {
var scroll = $window.scrollTop();
if (oldScroll != scroll) {
oldScroll = scroll;
if (scroll >= 1) {
navlogo.removeClass('nav-logo-before').addClass('nav-logo-after');
} else {
navlogo.removeClass('nav-logo-after').addClass('nav-logo-before');
}
}
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
});
body {
background-color: rgba(0,0,0,.2);
}
.space {
padding: 300px;
}
.nav-logo-before {
content: url(https://image.ibb.co/kYANyv/logo_test_before.png)
}
.nav-logo-after {
content: url(https://image.ibb.co/jYzFJv/logo_test_after.png)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img class="nav-logo nav-logo-before">
</div>
<div class="space">
</div>
Dont need to add the dot . in front of the class name in removeClass and addClass:
Use this:
navlogo.removeClass('nav-logo-before')
Secondly, you are removing the class that you are using to get the element in the first place.
I have an updated codepen, see if this suits your needs: http://codepen.io/anon/pen/ZeaYRO
You are removing the class nav-logo-before, so the second time the function runs, it can't find any element with nav-logo-before.
Just give a second class to your navlogo element and use that on line 3.
Like this:
var navlogo = $('.second-class');
working example:
http://codepen.io/anon/pen/ryYajx
You are getting the navlogo variable using
var navlogo = $('.nav-logo-before');
but then you change the class to be 'nav-logo-after', so next time the function gets called you won't be able to select the logo using jquery as it won't have the '.nav-logo-before'class anymore.
You could add an id to the logo and use that to select it, for example.
Apart from that, removeClass('.nav-logo-before') should be removeClass('nav-logo-before') without the dot before the class name.
The problem is that you removes nav-logo-before and then you want to select element with such class but it doesn't exist.
I've rafactored you code to avert it.
Another problem is that you uses dot in removeClass('.before') while it should be removeClass('before') - without dot
$(function() {
var navlogo = $('.nav-logo');
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 1) {
navlogo.removeClass('before').addClass('after');
} else {
navlogo.removeClass('after').addClass('before');
}
});
});
body {
background-color: rgba(0,0,0,.2);
}
.space {
padding: 300px;
}
.before {
content: url(https://image.ibb.co/kYANyv/logo_test_before.png)
}
.after {
content: url(https://image.ibb.co/jYzFJv/logo_test_after.png)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img class="nav-logo before">
</div>
<div class="space">
</div>

Removing javascript logo function with a css class

i have a page with a logo that changes his color by scrolling the page. I want to keep this function except for some page, so i want to remove this function.
How i could remove the effect if i insert a css class in the code?
var b = $(window).scrollTop();
if( b > 60 ){
$(".navbar").addClass("scroll-fixed-navbar");
$(".navbar-brand img").attr('src', 'img/dark-logo.png');
} else {
$(".navbar").removeClass("scroll-fixed-navbar");
$(".navbar-brand img").attr('src', 'img/white-logo.png');
}
});
$(document).ready(function() {
"use strict";
for esample i want to insert if class contain "black", so keep only the dark logo (the previous function will be disabled)
Wrap the current javascript with this:
if (!$(someElement).hasClass("black")) {
//do stuff here
}
This will prevent the class="black" from running that script, I cannot help any further since all your code is not posted but this will certainly point you in the right direction.

How can I hide a button when scrolled to the top of a page?

I'm trying to adapt this JSFiddle to make the menu button on my website hide when I'm at the top of the page and show when I start scrolling down.
I modified the JS to match the CSS on my site. Then I placed it in tags in the head of my page
var $scb = $('<div class="toggle-menu-wrap"></div>');
$('.top-header').append($scb);
var $ccol = $('.content');
$ccol.scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
However, it still doesn't work. Am I making a mistake in how I'm modifying the JS to fit my CSS?
You can include the toggle-menu-wrap element in your HTML from the start. There is no need to insert it using JS.
Write the one line of CSS you need, which is to hide the element from the beginning
.toggle-menu-wrap {
display: none;
}
Your version of jQuery uses 'jQuery' instead of '$' to reference itself. I would also re-write your JS like:
jQuery(document).ready(function() {
fadeMenuWrap();
jQuery(window).scroll(fadeMenuWrap);
});
function fadeMenuWrap() {
var scrollPos = window.pageYOffset || document.documentElement.scrollTop;
if (scrollPos > 300) {
jQuery('.toggle-menu-wrap').fadeIn(300);
} else {
jQuery('.toggle-menu-wrap').fadeOut(300);
}
}
Like #murli2308 said in the comments above, you need to attach a scroll event listener to the window:
$(document).ready(function () {
var $scb = $('<div class="scroll-border"></div>');
$('.above').append($scb);
var $ccol = $('.content');
$(window).scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
})
Wrapping your code in $(document).ready() would also be a good idea.
The reason $ccol.scroll(function() { ... works in that fiddle is because of the CSS:
.content{
height: 200px;
width: 200px;
overflow: auto;
}
Notice overflow: auto;. This causes that specific div to be scrollable. However, on your website, you scroll the entire page, not $ccol. This means the event handler will never fire a scroll event (since $ccol will never scroll).
You might have forgotten to link Jquery.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Link this inside your head tag incase.....
This should do the job:
$(window).scroll(function(e){
if ($(this).scrollTop() > 0) {
$(".your_element").css("display", "block");
} else {
$(".your_element").css("display", "none");
}
});

Categories