JavaScript/jQuery - scroll up button - javascript

I'm new to web development and came across a lot of tutorials on jQuery but there wasn't a lot on pure JS. I'm trying to convert this piece of code I found online which scrolls the page up when user clicks a button in the bottom right into pure JavaScript but I'm having some trouble.
function main() {
$('.back-to-top').hide();
$(window).scroll(function(){
if($(window).scrollTop()>400){
$('.back-to-top').fadeIn('fast');
}else{
$('.back-to-top').fadeOut('fast');
}
})
$('.back-to-top').click(function(){
$('body').animate({
scrollTop: 0
}, 1000)
return false;
})
}
This is what I have so far but it doesn't work:
var scrollUp = document.getElementsByClassName('back-to-top');
window.onscroll = function(){
if(window.pageYOffset >= 400){
scrollUp.style.display = 'block';
}else{
scrollUp.style.display = 'none';
}
}
scrollUp.onclick = function(){
window.scrollTo(0,0);
}
HTML
<a class="back-to-top" id="back-to-top" href="#">
<i class="fa fa-arrow-up" aria-hidden="true"></i>
<h2 class="text">Scroll Up</h2>
</a>
This is for web development assignment, can I have some advice?

The problem is that document.getElementsByClassName('back-to-top') returns an array-like object. Check documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
Solution:
var scrollUp = document.getElementsByClassName('back-to-top')[0];
window.onscroll = function(){
if(window.pageYOffset >= 400){
scrollUp.style.display = 'block';
}else{
scrollUp.style.display = 'none';
}
}
scrollUp.onclick = function(){
window.scrollTo(0,0);
}
See working example here:
https://jsfiddle.net/9m7doq1m/
To avoid this issue, you can use the id selector (getElementById) instead of the class selector.

var scrollUp = document.getElementsByClassName('back-to-top');
scrollUp.onclick = function(){
window.scrollTo(0,0);
}
#content {
height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content" style="height:1000px">
</div>
<a class="back-to-top" id="back-to-top" href="#">
<i class="fa fa-arrow-up" aria-hidden="true"></i>
<h2 class="text">Scroll Up</h2>
</a>

Related

How do I hide the menu when I click outside?

There is a website, there is a mobile version. The mobile version has a drop-down menu. This menu works fine, but it doesn't close when clicked outside the block.
I've been looking for a solution on the Internet for a really long time, but nothing came up( I'll be very grateful for the help!
HTML
<header class="header" id="header">
<div class="container">
<div class="header__inner" id="header">
<div class="header__logo">
<img src="Images/ActiveBox_logo.png" alt="Logo" class="img__logo">
</div>
<nav class="nav" id="nav">
Features
Works
Our Team
Testimonials
Download
</nav>
<button class="burger" type="button" id="navToggle">
<span class="burger__item">Menu</span>
</button>
</div> <!-- header__inner -->
</div>
</header>
JS
let header = $("#header");
let intro = $("#intro");
let introH = intro.innerHeight();
let scrollPos = $(window).scrollTop();
let nav = $("#nav");
let navToggle = $("#navToggle");
checkScroll(scrollPos, introH);
$(window).on("scroll resize", function() {
introH = intro.innerHeight();
scrollPos = $(this).scrollTop();
checkScroll(scrollPos, introH);
});
function checkScroll(scrollPos, introH) {
if( scrollPos > introH ) {
header.addClass("fixed");
} else {
header.removeClass("fixed");
}
}
/* Smooth scroll */
$("[data-scroll]").on("click", function(event) {
event.preventDefault();
let elementId = $(this).data('scroll');
let elementOffset = $(elementId).offset().top;
nav.removeClass("show");
$("html, body").animate({
scrollTop: elementOffset - 70
}, 700);
});
// Nav Toggle
navToggle.on("click", function(event) {
event.preventDefault();
nav.toggleClass("show");
});
How about something like this?
$(document).on('click', function (e) {
if ($(e.target).closest("#box").length === 0) {
$("#box").hide();
console.log('clicked outside the box');
}
else {
console.log('clicked on the box');
}
});
#box{
width:100px;
height:40px;
background-color:blue;
color:white;
padding:5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='box'>
click me, then click outside
</div>

JavaScript getElementById not working on mobilephone

I'm creating a website which has some JavaScript code. Everything of that JavaScript is working fine on the computer. But on my iPhone 7 the getElementById function does not work. I try to set a source of an img tag but nothing happens.
JavaScript:
var header_bar = $('.js-header-bar, .js-header-bar-mobile');
var header_bar_mobile = $('.js-header-bar-mobile');
var header_bar_navbar = header_bar_mobile.find('.navbar-primary');
var header_bar_toggler = header_bar_mobile.find('.navbar-toggler');
var header_bar_offsetTop = header_bar.offset().top;
$(window).on('scroll', onScroll);
function onScroll(){
if ($(this).scrollTop() > header_bar_offsetTop){
header_bar.addClass("sticky");
document.getElementById("headerLogo").src = "images/logo-black.png";
} else {
header_bar.removeClass("sticky");
document.getElementById('headerLogo').src = "images/logo-white.png";
}
}
The function should add at the top of the site a black logo and if I scroll a white logo.
On the computer it works but on my smartphone not.
HTML:
<header class="header header-mobile js-header-bar-mobile d-md-none">
<div class="header-bar">
<div class="header-bar-logo">
<a href="index.html">
<img class="originalTest" alt='Auto mit Schriftzug: "Autohandel-ZAR"' id="headerLogo" src="images/logo-white.png"/>
</a>
</div>
<div class="header-bar-menu">
<button class="navbar-toggler hamburger" type="button" id="js-header-toggle">
<span class="hamburger-box">
<span class="hamburger-inner"></span>
</span>
</button>
</div>
</div>
Thank you in advance.
Add an additional event listener for mobile devices:
$(document.body).on('touchmove', onScroll);
so the complete code should looks like:
var header_bar = $('.js-header-bar, .js-header-bar-mobile');
var header_bar_mobile = $('.js-header-bar-mobile');
var header_bar_navbar = header_bar_mobile.find('.navbar-primary');
var header_bar_toggler = header_bar_mobile.find('.navbar-toggler');
var header_bar_offsetTop = header_bar.offset().top;
$(document.body).on('touchmove', onScroll);
$(window).on('scroll', onScroll);
function onScroll(){
if ($(this).scrollTop() > header_bar_offsetTop){
header_bar.addClass("sticky");
document.getElementById("headerLogo").src = "images/logo-black.png";
} else {
header_bar.removeClass("sticky");
document.getElementById('headerLogo').src = "images/logo-white.png";
}
}
I solved the problem by getting the element with jQuery by class and not by Id
so the issue was the Id part.
Working Code:
function onScroll(){
if ($(this).scrollTop() > header_bar_offsetTop){
header_bar.addClass("sticky");
$(".logoHeader").attr("src", "images/logo-black.png");
} else {
header_bar.removeClass("sticky");
$(".logoHeader").attr("src", "images/logo-white.png");
}
}

Jquery code doesn't work with javascript

I'd like to make the header paragraph disappear at a certain width (say 1024px width) when the menu button is toggled.
As soon as I add the Jquery code the browser returns an error (ReferenceError: openSide is not defined) that doesn't exist if I comment the Jquery code.
I don't now if Jquery has been written thoroughly, but so far I cannot go through this issue
html:
<div id="header">
<header id="title">
<h1 style="font-size: 70px; font-weight: 600">The Nest</h1>
<p style="font-size: 40px">The hostel where your journey should start</p>
<button type="button" class="btn btn-lg" id="menu-btn" onclick="openSide()">
<span class="glyphicon glyphicon-list"></span>
</button>
</header>
</div>
<div id="sidebar">
×
Accomodations
Services
Merchandising
About us
</div>
Javascript:
function openSide() {
document.getElementById("sidebar").style.width = "350px";
//document.getElementById("header").style.backgroundPosition = "-250px";
document.getElementById("title").style.marginRight = "350px";
//document.getElementById("header").style.background = "linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5))";
}
function closeSide() {
document.getElementById("sidebar").style.width = "0";
//document.getElementById("header").style.backgroundPosition = "0px";
document.getElementById("title").style.marginRight = "0px";
}
var main = function() {
if (max-width = 1024px) {
$("#menu-btn").click(function() {
$("#title p").hide();
});
}
}
$(document).ready(main);
thx for your help
Your using the assignment operator instead of the equal operator. Your code should be:
$(document).ready(() => {
// Your condition here
if (true) {
$('#menu-btn').click(function() {
$('#title').hide();
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="menu-btn">Hide content</button>
<div id="title">foo</div>
Btw, in the code that you posted, the variable max-width is not a valid variable name and also you are not defining it.

Hide and Unhide div with the same button

I am using a code that unhides a hidden div.
HTML:
<div id="unhide" style="display:none;">DUMMY TEXT</div>
<button id="expand" name="expand">Show The Div</button>
JS:
document.getElementById("expand").addEventListener("click", function()
{
document.getElementById('unhide').style.display = "block";
});
How can I make the same button hide the div after clicking it again? Is it possible to alter the code I am using now?
use toggle to simple hide and unhide div
$("#expand").click(function() {
$("#unhide").toggle();
});
Use toggle for this show and shide, see below code.
$(document).ready(function(){
$("#expand").click(function(){
$("#unhide").toggle();
});
});
By doing some modifications in JavaScript, you can use the same button to hide the div as well as you can change the button text like below.
JS:
document.getElementById("expand").addEventListener("click", function()
{
var displayDiv = document.getElementById('unhide');
var displayValue = (displayDiv.style.display === "block") ? "none" : "block";
this.innerHTML = (displayValue === "block") ? "Hide The Div" : "Show The Div";
displayDiv.style.display = displayValue;
});
Link reference: https://jsfiddle.net/pitchiahn/hctnvsz1/1/
use simple if-else control flow
document.getElementById("expand").addEventListener("click", function()
{
var elem = document.getElementById('unhide');
if(elem.style.display == "none") { elem.style.display = "block"; }
else { elem.style.display = "none"; }
});
You can use .toggle()
$('#buttonId').on('click', function(e){
$("#DivId").toggle();
$(this).toggleClass('class1')
});​
.class1
{
color: orange;
}​
use toggleClass() to toggle the class for the button
$('#buttonLogin').on('click', function(e){
$("#login_Box_Div").toggle();
$(this).toggleClass('class1')
});​
.class1
{
color: orange;
}​
document.getElementById("expand").addEventListener("click", function()
{
if(document.getElementById('unhide').style.display == 'block')
document.getElementById('unhide').style.display = 'none';
else
document.getElementById('unhide').style.display = 'block';
});
you can check the running snippet here
this is pure java script
var button = document.getElementById('button'); // Assumes element with id='button'
button.onclick = function() {
var div = document.getElementById('newpost');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
};
This worked very well for me, hope it can help someone else. it opens a hidden div in an absolute position and closes it with the same button or the button in the div.
I use it for menu functions.
<div id="myDiv6" style="border:1px solid;background: rgba(255, 255, 255,
0.9);display: none;position: absolute; top: 229px; left: 25%; z-
index:999;height: auto;
width: 500px;">
<h2 >menu item</h2>
what ever you want in the hidden div
<button style="cursor: pointer;border-radius: 12px;background-image: linear-
gradient(to right, red,yellow);font-size:16px;"
onclick="changeStyle6()">Close</button>
</div>
<br/>
<button style="cursor: pointer;border-radius: 12px;background-image: linear-
gradient(to right, red,yellow);font-size:16px;width: 125px;"
onclick="changeStyle6()">button text</button><br/>
<script type="text/javascript">
function changeStyle6(){
var element = document.getElementById("myDiv6");
if(element.style.display == "none") { element.style.display = "block"; }
else { element.style.display = "none"; }
}
</script>

how do I use the same link to "re-hide" previously hidden text via Javascript?

The below code snippet shows the invite code when I click "Invite Code". But how do I re-hide the invite code if the same link is clicked again? And can it be done where it cycles back and forth with subsequent clicks? I didn't write this code but merely modified it to my use. I am still very new to this type of thing. Thanks!
<style>
div.hide { display:none; }
div.show { text-align:center; }
</style>
<script type='text/javascript'>
function showText(show, hide) {
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
</script>
<br>
<font color="red">-</font>Home<font color="red"> / </font><a onclick="showText('text1')" href="javascript:void(0);">Invite Code</a>-</font>
<div id="text1" class="hide"><font color="red">abc123</font></div>
</center></h3>
Simply use this function:
function showText(id)
{
var elem = document.getElementById(id);
if(elem.style.display == 'none')
{
elem.style.display = 'inline';
}
else
{
elem.style.display = 'none';
}
}
<a onClick="showText('text1');" href="#">Show or Hide</a><br/>
<div style="height: 30px;"><div id="text1" style="display: none;">Text to hide or show... WTF?!</div></div>
<div>This text should not move.</div>
PS: This also works for 2 Elements...
Greetings
I really don't see the use for the show class. You could just toggle the hide class on the elements that you want to toggle.
Assume you dont need the show class, then use the classList.toggle function like this
function toggle(target){
document.getElementById(target).classList.toggle('hide');
}
.hide{ display:none }
<button onclick="toggle('test')">Show / Hide</button>
<div id="test" class="hide">Hello world!</div>
save the state with a boolean
var hided = true;
function showText(show,hide){
if (hided){
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
else{
document.getElementById(show).className = "hide";
document.getElementById(hide).className = "show";
}
hided = !hided;
}
fiddle with this code and some of your html : fiddle,
isn't it the expected behavior ?
<html>
<div ID="content" style="display:block;">This is content.</div>
<script type="text/javascript">
function toggleContent() {
// Get the DOM reference
var contentId = document.getElementById("content");
// Toggle
contentId.style.display == "block" ? contentId.style.display = "none" :
contentId.style.display = "block";
}
</script>
<button onclick="toggleContent()">Toggle</button>
</html>
//Code is pretty self explanatory.

Categories