Hiding and showing sidebar div - javascript

I have a site here and I want to hide and show the sidebar with a button in the header but it is not working. Here is what I have tried:
<div id="B">
<button>toggle</button>
</div>
$('button').toggle(function() {
$('#sidebarright').animate({ left: 0 })
}, function() {
$('#sidebarright').animate({ left: 200 })
})
Nothing happens. Could you help me find out the problem?

The toggle() functionality you're trying to use has now been deprecated and removed from the latest versions of jQuery. To replicate it you can use the click() event with a simple ternary expression. Try this:
$('button').click(function() {
var $el = $('#sidebarright');
$el.animate({
left: parseInt($el.css('left'), 0) == 0 ? 200 : 0
});
});
Also note that the page you link to on your website does not contain a reference to jQuery. Here's how you should do that, along with a full implementation of the above code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
$(function() {
$('button').toggle(function() {
var $el = $('#sidebarright');
$el.animate({
left: parseInt($el.css('left'), 0) == 0 ? 200 : 0
});
});
});
</script>
</head>
Also note that you can simplify this by using CSS transitions only and toggling a class:
#sidebarright {
/* UI styling rules here */
left: 0;
transition: left 0.5s
}
#sidebarright.open {
left: 200;
}
$('button').click(function() {
$('#sidebarright').toggleClass('open');
});

You are using jQuery Script but you have not attached jQuery file in header.
Please add jQuery File in header.
Download it from http://www.jquery.com

Related

Saving dark mode after refresh

I have some code that saves my dark theme after refresh:
(thanks to https://stackoverflow.com/users/519413/rory-mccrossan on this post: Day/Night Toggle Using Cookie to Save on Page Refresh )
jQuery(document).ready(function($) {
$(".theme__switch").on("click", () => {
$(".theme__switch").toggleClass("active");
$("body").toggleClass("dark__theme");
$.cookie("toggle", $(".theme__switch").hasClass('active'));
});
if ($.cookie("toggle") === "true") {
$(".theme__switch").addClass("active");
$("body").addClass("dark__theme");
}
});
The only issue I find with this solution is that it flashes the original state before adding active to the toggle. So it flashes the original white background before adding the dark theme class. Is there a solution to avoid the flicker? or is this as good as it gets
The reason is that your code under jQuery(document).ready function runs when the page fully loaded. So, you have a delay to see its result and see the flashing.
There is no choice in framework-less websites except adding a loading frame fit to the total page at first and add a code to remove it after jQuery comes ready.
Assume this for example:
html
<div id="overlay">
<!-- some loading text or elements -->
</div>
css
#overlay {
position: fixed;
top: 0;
right: 0;
left: 0;
bottom: 0;
background: #fff;
}
js
jQuery(document).ready(function($) {
$(".theme__switch").on("click", () => {
$(".theme__switch").toggleClass("active");
$("body").toggleClass("dark__theme");
$.cookie("toggle", $(".theme__switch").hasClass('active'));
});
if ($.cookie("toggle") === "true") {
$(".theme__switch").addClass("active");
$("body").addClass("dark__theme");
}
jQuery('#overlay').hide();
});

jQuery doesn't add class to element

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

Toggle class of sticky menu on scroll with overflow hidden on page

I want to add a class .custom-menu-bg to sticky menu .custom-menu on scroll, while having overflow: hidden on body. Here's my code :
<script type="text/javascript" src="css/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var _rys = jQuery.noConflict();
_rys("document").ready(function() {
_rys(window).scroll(function() {
if (_rys(this).scrollTop() > 1) {
_rys('.custom-menu').addClass("custom-menu-bg");
} else {
_rys('.custom-menu').removeClass("custom-menu-bg");
}
});
});
</script>
But this code doesn't work with overflow: hidden on body tag
so I tried :
$('html').on('DOMMouseScroll', function(e) {
var delta = e.originalEvent.detail;
if (delta < 0) {
if ($('body').hasClass('section-element-1'))
$('.custom-menu').addClass("custom-menu-bg");
} else if (delta > 0) {
$('.custom-menu').removeClass("custom-menu-bg");
}
});
But this code only works for Mozilla and it's not a solution even, it's just a temp fix or work-around.
What I want is when I scroll down $('.custom-menu').addClass("custom-menu-bg"); i.e. custom-menu-bg class gets added to custom-menu.
And when I scroll up to the top $('.custom-menu').removeClass("custom-menu-bg"); i.e. custom-menu-bg class gets removed from custom-menu.
The top of body,document,window etcetera is always 0.
And top of my div with class custom-menu also has top: 0 always.
I'm looking for a permanent solution which works on all browsers.
I've reproduced the same effect you wanted HERE.
The only change that I've brought in comparison to your code is that I've made a makeshift body div and applied overflow: hidden on it.
Then, using jQuery, you'll be checking for the scroll event triggered by a wrapper inside the body div - which is in charge of holding the content) - and not by itself (or even document).
$('.wrapper').scroll(function () {
if ($(this).scrollTop() > 0) {
$('.custom-menu').addClass("custom-menu-bg");
} else {
$('.custom-menu').removeClass("custom-menu-bg");
}
});
This is because the makeshift body div has an overflow property set to hidden, and therefore won't generate that particular scroll event (maybe it would if you had the handler registered using browser-specific scroll events). Whereas the inner wrapper div will always have it's height property determined by it's content and is therefore scrollable.
NOTE: jQuery's scroll() is cross-browser, and hence a permanent solution.
You can bind on any id or on class also . its on you for now demo i
am using window .
This single event works for both if you have scroll or not. i.e overflow:hidden or overflow:scroll
$(window).bind('mousewheel DOMMouseScroll', function(event){
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
// scroll up
$('.custom-menu').removeClass("custom-menu-bg");
}
else {
// scroll down
$('.custom-menu').addClass("custom-menu-bg");
}
});
.custom-menu {
background-color: black;
height: 100px;
width: 100%
}
.custom-menu-bg{
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-menu">
</div>
Or you can also use this jQuery mousewheel plugin https://github.com/brandonaaron/jquery-mousewheel.
//toggled is class when mobile menu is opened
let moveScroll = '';
window.onscroll = function (e) {
const navBar = document.getElementById('id-of-your-navigation-bar');
if (moveScroll > 0 && navBar.classList.contains('toggled')) {
navBar.classList.remove('toggled');
moveScroll = 0;
} else if (navBar.classList.contains('toggled')) {
moveScroll = 1;
}
};

Creating a toggle on click

I am trying in jQuery to click a link and the content within it then comes in to 0px from the right of the screen. Then when you click it again, It closes, a kind toggle effect.
My current jQuery is:
$('.bet-slip-outer').click(function() {
// Responsive Stuff...
var windowwidth = $(window).width();
$('.bet-slip').animate({
'right': '-240px'
});
}, function() {
$('.bet-slip').animate({
'right': '0px'
});
});
However when I click the .bet-slip the right:-240 just seems to take precedence.
What am I doing wrong?
Cheers
with conditional:
define right style.
<div class="bet-slip" style="right:0px;"></div>
jquery
$('button').click(function() {
if($('.bet-slip').css('right') === '0px' ){
$('.bet-slip').animate({'right':'-240px'});
} else {
$('.bet-slip').animate({'right':'0px'});
}
});
other
only style:
$('button').click(function(){
$('div').toggleClass('right');
});
div{
position:relative;
width:100px;
height:10px;
background:green;
right:-100px;
transition:1s;
}
.right{
right:0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>
<button>
f
</button>
Use a variable to check if the element has been clicked yet.
toggle = "on";
$('.bet-slip-outer').click(function() {
// Responsive Stuff...
var windowwidth = $(window).width();
if(toggle == "on"){
$('.bet-slip').animate({
'right': '0px'
});
toggle = "off";
}else{
$('.bet-slip').animate({
'right': '-240px'
});
}
});
According to the official documentation, the .click() method only accepts a single handler. You cannot declare two different handlers for that purpose. There are two solutions to that — one is to delegate the animation to CSS, and use .toggleClass() instead, or to use stateful code:
Store the toggle status of the element in its own jQuery data object
Read the data object. If it doesn't exist or is 0, do something (condition 1)
If it exists and is 1, do something else (condition 2)
You can of course modify the binary conditions 1 and 2 into the effect you want to achieve.
In addition, in order to prevent jerky animation due to rapid clicking/toggling, you should stop the animation before you more animations to the queue. This is done by chaining .stop(true, true) to the object.
$(function() {
$('.bet-slip-outer').click(function() {
// Check state
if(!$(this).data('toggle') || $(this).data('toggle') == 0) {
$(this).data('toggle', 1);
$('.bet-slip').stop(true, true).animate({
'right': '-240px'
});
} else {
$(this).data('toggle', 0);
$('.bet-slip').stop(true, true).animate({
'right': '0'
});
}
});
});
.bet-slip {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bet-slip-outer">
<div class="bet-slip">bet-slip</div>
</div>
QUITE HARDING-CODING STYLE VARIABLES IN JS!
You could do something like:
$( ".bet-slip-outer .bet-slip" ).toggleClass( "animation" );
Then in your CSS you would do:
.bet-slip-outer .bet-slip { right: 0px;}
.animation { right: -240px;}
Why to use this option over others?
Your not hard-coding STYLE variables in your java-script your leaving that to CSS (what it's made for). As the project grows if you keep hard-coding it will eventually make your JS code base 'smell.' IE: I pain to change down the road!

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