So I have this page that I setup a sticky navbar and then a content below, with different sections. At the beginning of each section, there's a div that acts like an anchor, for which I have a working script so that it will scroll to that div once there's been a click on one of the menu's items.
The thing is: I need that anchor div's padding-bottom to be of equal size to the height of the menu, so that when the user clicks on a menu item and the page is scrolled, it reaches the beginning of its corresponding section. This doesn't work too well, maybe because I'm not a jQuery expert.
As well, the second trick is, when the page is being resized, the menu's height changes, and so I set up an event listener so that the padding-bottom of the anchor div (.test class div ) is set equal to the new height of the div. Here is a link for the online page with all the above as well as the link to a codepen. Thank you!
http://canonseverywhere.net/test/test-mason/index.html
https://codepen.io/andra-vilcu/pen/mdpgBmY
/*my function for setting the padding-bottom for the scroll-to div class test the size of the height of the sticky navbar, so that it scrolls to it; and here is where the issue lies; this is ment for window resizing too, when the navbar fiv has a different height; and i want the .test div to have the padding-bottom equal to the size of that height, so that it shows the beginning of each sectionb on scroll;*/
/*var GetInnerHeight = $("div#navbar").innerHeight();*/
var GetInnerHeight = $(".grid").innerHeight();
$('.test').css("paddingBottom", GetInnerHeight);
$(document).ready(function() {
$(window).resize(function() {
var GetInnerHeight = $(".grid").innerHeight();
$('.test').css("background-color", "pink");
});
});
/*END*/
/*the isotop JS that works fine*/
// external js: isotope.pkgd.js
// init Isotope
var $grid = $('.grid').isotope({
itemSelector: '.element-item',
layoutMode: 'fitRows',
getSortData: {
name: '.name',
symbol: '.symbol',
number: '.number parseInt',
category: '[data-category]',
weight: function(itemElem) {
var weight = $(itemElem).find('.weight').text();
return parseFloat(weight.replace(/[\(\)]/g, ''));
}
}
});
// filter functions
var filterFns = {
// show if number is greater than 50
numberGreaterThan50: function() {
var number = $(this).find('.number').text();
return parseInt(number, 10) > 50;
},
// show if name ends with -ium
ium: function() {
var name = $(this).find('.name').text();
return name.match(/ium$/);
}
};
// bind filter button click
$('#filters').on('click', 'button', function() {
var filterValue = $(this).attr('data-filter');
// use filterFn if matches value
filterValue = filterFns[filterValue] || filterValue;
$grid.isotope({
filter: filterValue
});
});
// bind sort button click
$('#sorts').on('click', 'button', function() {
var sortByValue = $(this).attr('data-sort-by');
$grid.isotope({
sortBy: sortByValue
});
});
// change is-checked class on buttons
$('.button-group').each(function(i, buttonGroup) {
var $buttonGroup = $(buttonGroup);
$buttonGroup.on('click', 'button', function() {
$buttonGroup.find('.is-checked').removeClass('is-checked');
$(this).addClass('is-checked');
});
});
/*end isotope js*/
/*beginning of scroll js script that works fine as well*/
function scrollFunction1() {
let e = document.getElementById("test1");
e.scrollIntoView({
block: 'start',
behavior: 'smooth',
inline: 'start'
});
}
function scrollFunction2() {
let e = document.getElementById("test2");
// This ends the block to the window
// bottom and also aligns the view to the center
e.scrollIntoView({
block: 'start',
behavior: 'smooth',
inline: 'start'
});
}
function scrollFunction3() {
let e = document.getElementById("test3");
// This ends the block to the window
// bottom and also aligns the view to the center
e.scrollIntoView({
block: 'start',
behavior: 'smooth',
inline: 'start'
});
}
function scrollFunction4() {
let e = document.getElementById("test4");
// This ends the block to the window
// bottom and also aligns the view to the center
e.scrollIntoView({
block: 'start',
behavior: 'smooth',
inline: 'start'
});
}
function scrollFunction5() {
let e = document.getElementById("test5");
// This ends the block to the window
// bottom and also aligns the view to the center
e.scrollIntoView({
block: 'start',
behavior: 'smooth',
inline: 'start'
});
}
function scrollFunction6() {
let e = document.getElementById("test6");
// This ends the block to the window
// bottom and also aligns the view to the center
e.scrollIntoView({
block: 'start',
behavior: 'smooth',
inline: 'start'
});
}
function scrollFunction7() {
let e = document.getElementById("test7");
// This ends the block to the window
// bottom and also aligns the view to the center
e.scrollIntoView({
block: 'start',
behavior: 'smooth',
inline: 'start'
});
}
function scrollFunction8() {
let e = document.getElementById("test8");
// This ends the block to the window
// bottom and also aligns the view to the center
e.scrollIntoView({
block: 'start',
behavior: 'smooth',
inline: 'start'
});
}
function scrollFunction9() {
let e = document.getElementById("test9");
// This ends the block to the window
// bottom and also aligns the view to the center
e.scrollIntoView({
block: 'start',
behavior: 'smooth',
inline: 'start'
});
}
/*end of scroll script*/
* {
box-sizing: border-box;
}
body {
font-family: sans-serif;
}
/* ---- button ---- */
.button {
display: inline-block;
padding: 0.5em 1.0em;
background: #EEE;
border: none;
border-radius: 7px;
background-image: linear-gradient( to bottom, hsla(0, 0%, 0%, 0), hsla(0, 0%, 0%, 0.2));
color: #222;
font-family: sans-serif;
font-size: 16px;
text-shadow: 0 1px white;
cursor: pointer;
}
.button:hover {
background-color: #8CF;
text-shadow: 0 1px hsla(0, 0%, 100%, 0.5);
color: #222;
}
.button:active,
.button.is-checked {
background-color: #28F;
}
.button.is-checked {
color: white;
text-shadow: 0 -1px hsla(0, 0%, 0%, 0.8);
}
.button:active {
box-shadow: inset 0 1px 10px hsla(0, 0%, 0%, 0.8);
}
/* ---- button-group ---- */
.button-group {
margin-bottom: 7px;
}
.button-group:after {
content: '';
display: block;
clear: both;
}
.button-group .button {
float: left;
border-radius: 0;
margin-left: 0;
margin-right: 1px;
}
.button-group .button:first-child {
border-radius: 0.5em 0 0 0.5em;
}
.button-group .button:last-child {
border-radius: 0 0.5em 0.5em 0;
}
/* ---- isotope ---- */
.grid {
/*border: 1px solid #333;*/
}
/* clear fix */
.grid:after {
content: '';
display: block;
clear: both;
}
/* ---- .element-item ---- */
/*dimensiunea fiecarui element*/
.element-item {
position: relative;
float: left;
/*width: 75px;*/
width: auto;
min-width: 115px;
height: 37px;
margin: 3px;
padding: 6px;
background: #888;
color: #262524;
border: 0.5px solid #333;
}
.element-item>* {
margin: 0;
padding: 0;
}
.element-item .name {
position: absolute;
left: 10px;
top: 60px;
text-transform: none;
letter-spacing: 0;
font-size: 12px;
font-weight: normal;
}
.element-item .symbol {
position: absolute;
left: 10px;
top: 0px;
font-size: 14px;
font-weight: bold;
color: white;
width: auto;
}
.element-item .number {
position: absolute;
right: 8px;
top: 5px;
}
.element-item .weight {
position: absolute;
left: 10px;
top: 76px;
font-size: 12px;
}
.element-item.alkali {
background: #F00;
background: hsl( 0, 100%, 50%);
}
.element-item.alkaline-earth {
background: #F80;
background: hsl( 36, 100%, 50%);
}
.element-item.lanthanoid {
background: #FF0;
background: hsl( 72, 100%, 50%);
}
.element-item.actinoid {
background: #0F0;
background: hsl( 108, 100%, 50%);
}
.element-item.transition {
background: #0F8;
background: hsl( 144, 100%, 50%);
}
.element-item.post-transition {
background: #0FF;
background: hsl( 180, 100%, 50%);
}
.element-item.metalloid {
background: #08F;
background: hsl( 216, 100%, 50%);
}
.element-item.diatomic {
background: #00F;
background: hsl( 252, 100%, 50%);
}
.element-item.halogen {
background: #F0F;
background: hsl( 288, 100%, 50%);
}
.element-item.noble-gas {
background: #F08;
background: hsl( 324, 100%, 50%);
}
/*pana aici tine stylesul ptr izotop; de aici incepe stylesul ptr scrooll*/
.outer-wrapper {
margin: 0 auto;
width: 100%;
}
.outer-wrapper div {
margin: 0 auto;
width: 100%;
}
#element {
display: block;
height: auto;
width: auto;
overflow: auto;
margin: 10px auto 5px;
}
#el1 {
display: block;
height: auto;
width: 1000px;
}
#el1 div {
display: block;
height: auto;
width: 1000px;
}
#el1 p {
text-align: justify;
}
#el2 {
display: block;
height: auto;
width: 1000px;
}
#el2 div {
display: block;
height: auto;
width: 1000px;
}
#el2 p {
text-align: justify;
}
/* sticky menu css */
/* Style the navbar */
#navbar {
overflow: auto;
background-color: blue;
/*era #333*/
height: auto;
position: fixed;
width: 100%;
}
.test {
padding-top: 0;
margin-top: 0;
}
.test div {
padding-top: 0;
margin-top: 0;
}
<div id="navbar">
<div class="grid" style=" width:69%; margin:0 auto !important; text-align:center;">
<!-- de documentat -->
<div onclick="scrollFunction1()" class="element-item transition metal " data-category="transition">
<p class="symbol">Poetry</p>
<!-- <p class="number">80</p>
<p class="weight">200.59</p>-->
</div>
<div onclick="scrollFunction2()" class="element-item metalloid " data-category="metalloid">
<!-- <h3 class="name">Tellurium</h3>-->
<p class="symbol">Literature</p>
<!--<p class="number">52</p>
<p class="weight">127.6</p>-->
</div>
<div onclick="scrollFunction3()" class="element-item post-transition metal " data-category="post-transition">
<!--<h3 class="name">Bismuth</h3>-->
<p class="symbol">Games</p>
<!-- <p class="number">83</p>
<p class="weight">208.980</p>-->
</div>
<div onclick="scrollFunction4()" class="element-item post-transition metal " data-category="post-transition">
<!-- <h3 class="name">Lead</h3>-->
<p class="symbol">Music of my youth</p>
<!-- <p class="number">82</p>
<p class="weight">207.2</p>-->
</div>
<div onclick="scrollFunction5()" class="element-item transition metal " data-category="transition">
<!--<h3 class="name">Gold</h3>-->
<p class="symbol">Minimalism</p>
<!-- <p class="number">79</p>
<p class="weight">196.967</p>-->
</div>
<div onclick="scrollFunction6()" class="element-item alkali metal " data-category="alkali">
<!-- <h3 class="name">Potassium</h3>-->
<p class="symbol">Jazz</p>
<!-- <p class="number">19</p>
<p class="weight">39.0983</p>-->
</div>
<div onclick="scrollFunction7()" class="element-item alkali metal " data-category="alkali">
<!-- <h3 class="name">Sodium</h3>-->
<p class="symbol">Contemporary music</p>
<!-- <p class="number">11</p>
<p class="weight">22.99</p>-->
</div>
<div onclick="scrollFunction8()" class="element-item transition metal " data-category="transition">
<!-- <h3 class="name">Cadmium</h3>-->
<p class="symbol">Competitions</p>
<!-- <p class="number">48</p>
<p class="weight">112.411</p>-->
</div>
<div onclick="scrollFunction9()" class="element-item alkaline-earth metal " data-category="alkaline-earth">
<!--<h3 class="name">Calcium</h3>-->
<p class="symbol">neighbors</p>
<!-- <p class="number">20</p>
<p class="weight">40.078</p>-->
</div>
</div>
</div>
<!-- end sticky menu -->
<!-- begins the scrolling sections -->
<div class="outer-wrapper">
<div id="element" class="inner-wrapper">
<!-- clasa nealocat-->
<div id="test1" class="test" style="border:3px solid yellow;"></div>
<div id="el1">
<h1> TESTING PROCESS SECTION 1</h1><br>
<p>"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue;
and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. </p><br>
</div>
<div id="test2" class="test" style="border:3px solid red;"></div>
<!-- scroll to style="padding-bottom:80px;" -->
<div id="el2">
<h1>SECTION 2</h1>
<p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt
mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas
assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates. </p><br>
</div>
<div id="test3" class="test" style="border:3px solid pink;"></div>
<!-- scroll to style="padding-bottom:80px;" -->
<div id="el2">
<h1>SECTION 3</h1>
<p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt
mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas
assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus,
ut aut </p><br>
</div>
<div id="test4" class="test" style="border:3px solid purple;"></div>
<!-- scroll to style="padding-bottom:80px;" -->
<div id="el2">
<h1>SECTION 4</h1>
<p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt
mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo </p><br>
</div>
<div id="test5" class="test" style="border:3px solid red;"></div>
<!-- scroll to style="padding-bottom:80px;" -->
<div id="el2">
<h1>SECTION 5</h1>
<p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt
mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas
assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis </p><br>
</div>
<div id="test6" class="test" style="border:3px solid red;"></div>
<!-- scroll to style="padding-bottom:80px;" -->
<div id="el2">
<h1>SECTION 6</h1>
<p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt
mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas
assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis </p><br>
</div>
<div id="test7" class="test" style="border:3px solid red;"></div>
<!-- scroll to style="padding-bottom:80px;" -->
<div id="el2">
<h1>SECTION 7</h1>
<p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt
mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas
assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis </p><br>
</div>
<div id="test8" class="test" style="border:3px solid red;"></div>
<!-- scroll to style="padding-bottom:80px;" -->
<div id="el2">
<h1>SECTION 8</h1>
<p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt
mollitia animi, id est laborum et dolorum
</div>
<div id="test9" class="test" style="border:3px solid red;"></div>
<!-- scroll to style="padding-bottom:80px;" -->
<div id="el2">
<h1>SECTION 9</h1>
<p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt
mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas
assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis </p><br>
</div>
</div>
</div>
<!-- end outer wrapper -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://unpkg.com/isotope-layout#3/dist/isotope.pkgd.js"></script>
Since you mentioned you would like some help on how to simplify everything, I made a little demo to show how i would do it.
Disclaimer: i got no clue of isotope, so you might have to modify stuff.
I'll have to let you know i haven't tested it yet, but it should work and eliminate a lot of repetitive code. :)
Since you have a ton of divs with the same structure, it's simpler to create them with js than to manually write HTML for each one!
// you could dynamically create your elements in js, saves some headache
// when working with a lot of data.
// simply create an object with all the properties you need for your elements!
let obj1 = {
className: 'metal',
transition: True, // could use boolean if it can only be in or out of transition
text: 'Games'
}
let obj2 = {
className: 'metalloid',
transition: False,
text: 'Literature'
}
function createElementItem(myObj) {
// myObj is sort of a "template" for the property we will pass to this function.
// we will call the function below with our objects we just created
// you can create DOM elements by using <>, just don't forget to close!
// if you do not insert it somewhere, it won't show up though. See bottom.
let elem = $(`<div />`); // create div element
elem.addClass(myObj.className); // add the class name
let transition_name = myObj.transition ? 'transition' : 'post-transition';
// explanation: fancy ternary operator is fancy.
// the left part (myObj.transition) is a Boolean type. The '?' operator
// checks if the statement is true. If true, it returns the next option
// 'transition'. If false, it returns 'post-transition'.
elem.addClass(transition_name); // here we add the transition name.
elem.data('category', transition_name); // and also set data-transition to the same value.
let symbol_elem = $('<p class="symbol" />');
symbol_elem.text(myObj.text); // give symbol element your text
symbol_elem.appendTo(elem); // insert the symbol element in element div
let grid_elem = $('div.grid'); // select your grid, where you append element-items
elem.appendTo(grid_elem); // and finally append your whole element to the existing grid
// now the fun part: event listeners.
// since we are in the same function, it's easy to access each element!
elem.on('click', (e) => {
let elem = $(this); // in this case, $(this) refers to element that has been clicked
// you could also use $(e.target) instead of $(this)
console.log('they see me scrollin');
elem.scrollIntoView({
block: 'start',
behavior: 'smooth',
inline: 'start'
});
})
}
// here is where the magic happens.
// we invoke our function, passing the objects from the top as a param
// so the function can access the important stuff
// this spits out the object HTML, injects it into DOM and applies the event listener all-in-one
createElementItem(obj1);
createElementItem(obj2);
Regarding resize:
$(window).on('resize', (e) => {
// do not start variable names with Uppercase letters, this is
// reserved for classes!
let innerHeight = $(".grid").innerHeight();
$('.test').css("padding-bottom", innerHeight); // this SHOULD work...
});
// i think you're having a problem with putting the resize event
// listener in document.ready, but not 100% sure, would have to test
// since document.ready only executes once
OK, so I got this code that works. This is the scroll script
$(function(){
$('a[href^="#"]:not([href="#"])').click(function(){
$("html, body").animate({
scrollTop: $($(this).attr("href")).position().top
}, 500);
return false;
});
});
and then I got this to do the measurings of the reference position in comparison with the scroll position and all my a references have the class "tab"
function lineMove(){
$('.tab').each(function (){
var scrollPos = $(document).scrollTop();
var linkRef = $($(this).attr("href"));
var refPos = linkRef.position().top;
var refHeight = linkRef.height();
if(refPos <= scrollPos && refPos + refHeight > scrollPos){
$('.tab').removeClass("active-tab");
$(this).addClass("active-tab");
};
});
};
and of course
$(document).ready(function(){
//On document load:
lineMove();
//On window scroll or resize:
$(window).on("scroll resize", lineMove);
});
I want to mention that this code is part of another code that I found on the internet and that it is not my creation. However, I adapted it to work in this case.
Final solution: And then I worked a bit and I got this:
function paddingTop (){
var divHeight = $("div#id").innerHeight();
$("#testbeta").css("padding", divHeight); /
};
Comment: jQuery is nice!
This question already has answers here:
How do I detect a click outside an element?
(91 answers)
Closed 2 years ago.
I'm trying to find multiple ways to close a sidebar menu that pops out from the left side. The idea of this is to have a page with an "Open/Close Menu" button. As expected this button should be able to open and close the menu with clicked, but I also want to include an option of closing it when simply clicking outside the menu bar.
My thought process behind this is to add a div that surrounds all of the content on the page, and gives it a class name of "notMenu". I would define the dimensions of this to be the entire page and give it a z-index of 1. When the menu pops up, it would be on top of .notMenu with a z-index of 2, yet I can't seem to get it to work.
var menuBtn = document.querySelector('.menuBtn');
var sidebar = document.querySelector('.sidebar');
var closeMenuBtn = document.querySelector('.closeMenuBtn');
var notMenu = document.querySelector('.notMenu');
var nav = 'closed'
menuBtn.addEventListener('click', function() {
if (nav === 'closed') {
sidebar.style.display = 'block'
nav = 'open'
} else {
sidebar.style.display = 'none'
nav = 'closed'
}
});
// closeMenuBtn.addEventListener('click',function(){
// sidebar.style.display = 'none'
// });
closeMenuBtn.addEventListener('click', function() {
sidebar.style.display = 'none';
nav = 'closed';
});
/*
notMenu.addEventListener('click',function(){
sidebar.style.display = 'none'
nav = 'closed';
})
*/
h1 {
text-align: center;
}
.menuBtn {
position: relative;
left: 50%;
transform: translateX(-50%);
}
.closeMenu {
font-size: 30px;
z-index: 2;
}
.sidebar {
position: absolute;
top: 0;
height: 100vh;
width: 300px;
background: grey;
display: none;
z-index: 2;
}
.notMenu {
position: absolute;
top: 0;
height: 100%;
width: 100%;
z-index: 1;
}
<body>
<div class="notMenu">
<h1> Header </h1>
<div class="sidebar">
<ul>
<li><a href=''>Link1</a></li>
<li><a href=''>Link2</a></li>
<li><a href=''>Link3</a></li>
</ul>
<button class="closeMenuBtn">Close Menu</button>
</div>
<button class="menuBtn">Open/Close Menu</button>
<div class="content1">
<br><br> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Aspernatur quia ipsam optio, veritatis corrupti exercitationem quae itaque accusamus voluptas ipsa consequuntur nostrum, culpa, cum dolore incidunt ducimus harum minus doloremque?
</div>
<div class="content2">
<br><br> Lorem ipsum dolor sit amet consectetur adipisicing elit. Eum quia laboriosam ut accusantium itaque adipisci vitae error provident voluptate, dolorem veniam dignissimos atque accusamus aut rem quos esse fugit voluptas soluta laudantium.
Nam voluptates maxime sapiente, pariatur voluptatibus mollitia quia.
</div>
</div>
<!--closes .notMenu-->
</body>
CodePen Link
Alternatively, is there a way to do this without designated a new class as .notMenu? I assume there is a possibility to do this with e.target in JS with if statements.
function(e){
if (e.target !== 'sidebar'){
sidebar.style.display = 'none'
}
}
The issue I ran into with this is that e.target returns an object. I'm unable to define which objects represent the sidebar and which ones do not, therefore I can't determine if the area outside the sidebar is being clicked.
try this
window.addEventListener('mouseup', function(e) {
var x = document.querySelector('.sidebar');
if (event.target != document.querySelector(".icon")) {
x.style.display = "none";
}
});
var menuBtn = document.querySelector('.menuBtn');
var sidebar = document.querySelector('.sidebar');
var closeMenuBtn = document.querySelector('.closeMenuBtn');
var notMenu = document.querySelector('.notMenu');
var nav = 'closed'
menuBtn.addEventListener('click',function(){
if (nav === 'closed'){
sidebar.style.display='block'
nav = 'open'
}
else{
sidebar.style.display = 'none'
nav = 'closed'
}
});
closeMenuBtn.addEventListener('click',function(){
sidebar.style.display = 'none';
nav = 'closed';
});
// fire event if click is outside of sidebar and menubtn
window.onclick = function(event) {
if (event.target !== sidebar && event.target !== menuBtn) {
sidebar.style.display = "none";
console.log('clicked');
}
}
h1{
text-align:center;
}
.menuBtn{
position:relative;
left:50%;
transform:translateX(-50%);
}
.closeMenu{
font-size:30px;
z-index:2;
}
.sidebar{
position:absolute;
top:0;
height:100vh;
width:300px;
background:grey;
display:none;
z-index:2;
}
.notMenu{
position:absolute;
top:0;
height:100%;
width:100%;
z-index:1;
}
<div class="notMenu">
<h1> Header </h1>
<div class="sidebar">
<ul>
<li><a href =''>Link1</a></li>
<li><a href =''>Link2</a></li>
<li><a href =''>Link3</a></li>
</ul>
<button class="closeMenuBtn">Close Menu</button>
</div>
<button class="menuBtn">Open/Close Menu</button>
<div class="content1">
<br><br>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Aspernatur quia ipsam optio, veritatis corrupti exercitationem quae itaque accusamus voluptas ipsa consequuntur nostrum, culpa, cum dolore incidunt ducimus harum minus doloremque?
</div>
<div class="content2">
<br><br>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eum quia laboriosam ut accusantium itaque adipisci vitae error provident voluptate, dolorem veniam dignissimos atque accusamus aut rem quos esse fugit voluptas soluta laudantium. Nam voluptates maxime sapiente, pariatur voluptatibus mollitia quia.
</div>
</div>
try this
I am trying to create a simple Read More example. It consists of a paragraph and a button with half of the paragraph enclosed in a span tag which is initially set to hidden. When user clicks on Read More button the hidden span shows up. I have got the working code but just want to do a fade in effect like JQuery but with pure Javascript. Anyone please help.
var span = document.getElementsByTagName('span')[0];
var hideshow = document.getElementById('hideshow');
span.style.display = 'none';
hideshow.onclick = function() {
span.style.display = 'block';
};
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa maiores dolore earum ducimus molestiae, aut. <span>Quisquam consequuntur, maiores et, doloremque atque provident similique consequatur totam voluptas vitae veniam, molestiae laborum.</span></p>
<button id="hideshow">Read More</button>
One approach is to use a CSS3 transition in order to transition the element's opacity.
In the example below, the class fade-in is added to the child span element when clicking the button.
var button = document.querySelector('.read-more');
button.addEventListener('click', function(event) {
var span = event.target.previousElementSibling.querySelector('span');
span.classList.add('fade-in');
});
.show-more span {
display: inline-block;
height: 0;
overflow: hidden;
transition: opacity 2s;
opacity: 0;
}
.show-more span.fade-in {
height: auto;
opacity: 1;
}
<p class="show-more">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa maiores dolore earum ducimus molestiae, aut. <span>Quisquam consequuntur, maiores et, doloremque atque provident similique consequatur totam voluptas vitae veniam, molestiae laborum.</span></p>
<button class="read-more">Read More</button>
If you want an approach that works for multiple elements, you could also use the following:
var buttons = document.querySelectorAll('.read-more');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function(event) {
var span = event.target.previousElementSibling.querySelector('span');
span.classList.add('fade-in');
});
}
.show-more span {
display: inline-block;
height: 0;
overflow: hidden;
transition: opacity 2s;
opacity: 0;
}
.show-more span.fade-in {
height: auto;
opacity: 1;
}
<p class="show-more">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa maiores dolore earum ducimus molestiae, aut. <span>Quisquam consequuntur, maiores et, doloremque atque provident similique consequatur totam voluptas vitae veniam, molestiae laborum.</span></p>
<button class="read-more">Read More</button>
<p class="show-more">Another shorter paragraph. <span>Quisquam consequuntur, maiores et, doloremque atque provident similique consequatur totam voluptas vitae veniam, molestiae laborum.</span></p>
<button class="read-more">Read More</button>
Starting here
span.style.opacity = 0;
You'll need to gradually transition the opacity to here.
span.style.opacity = 1;
You'll need to use an asynchronous construct (setTimeout/setInterval/requestAnimationFrame) for iterating, because a synchronous one (while/for/for-in/forEach) will block the main thread, preventing the browser from actually rendering the element with the updated opacity.
function fadeIn(element) {
function transition() {
if(element.style.opacity < 1) {
requestAnimationFrame(transition);
element.style.opacity = Number(element.style.opacity) + 0.05;
}
}
transition();
}
Alternatively, if you're happy to use CSS (rather than pure JS) you can do this with classes and transitions.
.out {
opacity: 0;
transition-duration: 0.5s;
}
.in {
opacity: 1;
transition-duration: 0.5s;
}
Make sure that the element has the out class when it arrives in the DOM, then when you're ready to fade it in, swap it for the in class and the browser will handle the animation for you.
var duration = 2000; // msecs
document.getElementById('hideshow').onclick = () => {
requestAnimationFrame((start_time) => {
var anim = (time) => {
var p = (time - start_time) / duration;
(p < 1) && requestAnimationFrame(anim);
span.style.opacity = 1 - p;
}
anim(start_time);
})
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying to create a page with images that upon a user hovering loads content into a div on the same page. So far, I have created the html file and the stylesheet. It's a fairly simple, table-based page, with three images that have the css hover effect on them and link to three different pages. My challenge is figuring out how to load content into the div. I am completely new to Javascript so this is going to be quite the learning curve I imagine but any help will be appreciated. I have attached an image to illustrate what I am trying to do. Thanks everyone]1
Updated question. Thanks for your input everybody. (Back from the holidays - will be going over suggestions)
My css code:
.Image1{
background-image:url('Image1_REG.jpg');
height:86px;
width:86px;
display: block;
}
.Image1:hover {
background-image:url('Image1_Shadow.jpg');
height:86px;
width:86px;
display:block;
}
.Image2{
background-image:url('Image2_REG.jpg');
height:86px;
width:86px;
display: block;
}
.Image2:hover {
background-image:url('Image2_Shadow.jpg');
height:86px;
width:86px;
display:block;
}
.Image3{
background-image:url('Image3_REG.jpg');
height:86px;
width:86px;
display: block;
}
.Image3:hover {
background-image:url('Image3_Shadow.jpg');
height:86px;
width:86px;
display:block;
}
#contentDiv{
height:150px;
width:350px;
left:50px;
top:150px;
position:absolute;
background-color:#452835;}
table {
width:600px;
height:auto;
column-width:200px;
left:150px;
top:150px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="newStyle.css"></link>
</head>
<body>
<body>
<table>
<tbody>
<tr><img src="header.jpg" align ="center" /></tr>
<tr>
<td><a class="Image1" href="http://link1" target="_blank"></a>
</td>
<td>
<a class="Image2" href="http://link2" target="_blank"></a>
</td>
<td><a class="Image3" href="http://link3" target="_blank"></a></td>
</tr>
</tbody>
</table>
<div id="contentDetails">Where the hover text is to be displayed</div>
</body>
</html>
You'll need a small bit of JavaScript but nothing you can't learn in half an hour. I'd advise you read the MDN JS primer but only to get a grasp for how JS works.
In essence you need to locate the element you want to hover over and then have multiple <div>s on your page containing your content. You add a JavaScript mouseover event on the elements you want to hover over and in the callback function you supply to it you tell it to hide all the divs and then display only the div you want.
I think you should be able to work out everything from these pages:
How to get an element in JS
How to add a mouseover event
How to hide and show elements
Best of luck with it. If you're stuck once you've written some code feel free to edit your question and comment on mine (so I know to take a look) and I'll try help.
Here's a very basic example I created that will help get you started:
JS Fiddle:
http://jsfiddle.net/dvav1gdo/5/
HTML
<div class="module">
<div class="tabs">
<div class="tab">
<img style="-webkit-user-select: none;" src="http://dummyimage.com/200x150/000/fff.jpg" width="200" height="150">
</div>
<div class="tab">
<img style="-webkit-user-select: none;" src="http://dummyimage.com/200x150/000/fff.jpg" width="200" height="150">
</div>
<div class="tab">
<img style="-webkit-user-select: none;" src="http://dummyimage.com/200x150/000/fff.jpg" width="200" height="150">
</div>
</div>
<div class="tab-panels">
<div class="tab-panel active">
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit unde inventore, aliquam architecto minus minima quis. Aliquid voluptates, dolorum ullam dicta nesciunt molestiae maiores! Ratione quasi officia recusandae laboriosam nihil voluptate perferendis fugiat quae provident aliquam harum id tenetur quisquam, ab repellendus suscipit eligendi temporibus facilis sapiente a veniam voluptatibus quidem in voluptatum vero. Soluta excepturi quisquam, sed, quas rem aperiam atque obcaecati nulla repellendus corporis? Consequatur aut quidem, earum enim asperiores. Libero deserunt dignissimos blanditiis est, repellendus qui molestiae tenetur quas assumenda officiis modi totam, quae ullam. Quaerat officiis tempora molestias voluptatibus sint quo incidunt nostrum quisquam sed excepturi?</p>
</div>
</div>
<div class="tab-panel">
<div class="content">
<p>Lorem ipsum dolor sit amet.</p>
</div>
</div>
<div class="tab-panel">
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error fugit harum voluptates. Deserunt adipisci libero incidunt nostrum similique laborum dicta, porro natus harum odit, voluptatum vitae, minima iure omnis. Odit, nemo incidunt voluptas placeat est quis ab dolor. Iure, corporis.</p>
</div>
</div>
</div>
</div>
CSS
.tab {
display: inline-block;
}
.tab-panel {
display: none;
&.active {
display: block;
}
}
jQuery
$(document).ready(function () {
var $tabs = $('.tab');
var $panels = $('.tab-panel')
// attach js event handler to all tab jQuery objects
$tabs.on('mouseover', function() {
var $this = $(this);
// get hover index
var hindex = $this.index();
// use the active class to show and hide correct panel based on current hover index
$panels.removeClass('active');
$panels.eq(hindex).addClass('active');
});
});
You could use the hover or click function to detect interaction with the image then you use the div id/name to change the text with query i believe its should be $("").text("Some info")
example:
<div style="height:100px; width:100px" class="title"> //*
first text
</div>
The code that you need in order to change the text in the div which his class name is "title" (SEE comment "//*" above):
$('div.title').text('Some info');
Also See for more information "Use jquery to set value of div tag":
Use jquery to set value of div tag
LINKS:
http://api.jquery.com/text/
http://api.jquery.com/hover/
http://api.jquery.com/click/
Also you can use #tanjir 's code as example:
$('#img1').hover(function(){
$('#contentDiv').text("content for text 1")
};
Remember that
$('#img1'). hover(function(){
// CODE EXECUTE HERE AFTER HOVER OF IMAGE 1
}
*** this example has # in the start because he use the id of the div instead of the class name! so it would look like:
<div ID="img1">
</div>
Is a listener that wait you to hover, when you will hover the code where the comment is will execute.
I've got a responsive site I'm building Where I have two elements that overlap each other. THe size of the elements will change depending on the browser width as will the overlap and consequently I need to set left-padding on the right element dynamically.
I'm unsure of how to proceed with this. Have set up a Fiddle here.
html:
<div class="container">
<div class="row copy intro">
<section class="red">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor illum nobis ullam neque, harum, magni. Reprehenderit veritatis in deleniti incidunt dolore dolores ex id expedita.</p>
<p>Corporis soluta ducimus ut quasi libero nesciunt, eligendi autem, consequatur error sapiente labore, officia tempora in voluptas non deleniti veniam officiis, quis vero consequuntur quia!</p>
</section>
<section class="white">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor illum nobis ullam neque, harum, magni. Reprehenderit veritatis in deleniti incidunt dolore dolores ex id expedita.</p>
<p>Corporis soluta ducimus ut quasi libero nesciunt, eligendi autem, consequatur error sapiente labore, officia tempora in voluptas non deleniti veniam officiis, quis vero consequuntur quia!</p>
</section>
</div>
</div><!--container-->
css:
/* line 3, ../build/sass/_intro.scss */
.intro {
background: #0079c2;
position: relative;
padding: 15px;
padding-bottom: 150px;
}
/* line 9, ../build/sass/_intro.scss */
.intro section {
position: relative;
padding: 100px;
width: 60%;
-moz-border-radius: 500px;
-webkit-border-radius: 500px;
border-radius: 500px;
}
/* line 26, ../build/sass/_intro.scss */
.intro section.red {
background: rgba(238, 45, 36, 0.85);
color: #fff;
z-index: 200;
}
/* line 31, ../build/sass/_intro.scss */
.intro section.red h1 {
font-size: 24px;
}
/* line 45, ../build/sass/_intro.scss */
.intro section.white {
background: #fff;
color: #0079c2;
position: absolute;
top: 150px;
right: 15px;
}
js:
// set intro sections width = height
$(document).ready(function() {
var circleWidth= $('.intro section.red').outerWidth();
$('.intro section').css('min-height', circleWidth + 'px');
$('.intro section.white').css('width', circleWidth + 'px');
});
Thank you for your time.
Use % for padding and adjust accordingly. See this revised Fiddle for an example.
The revised Fiddle comments out:
$('.intro section.white').css('width', circleWidth + 'px');
Fixing the width of the white circle means that it is not responsive any more. If you need to do that for some reason, you would have to make adjustments.
Here's a JSFiddle doing what I think you want: http://jsfiddle.net/6yro5vhx/2/
Basically I user offset() & outerWidth() on the two elements to work out the overlap, and then call calculatePadding() function on documentready & resize events.
function calculatePadding() {
var white = $('.intro section.white');
var red = $('.intro section.red');
var extraPadding = 20;
var distanceLeft = white.offset().left;
var redDistanceRight = red.offset().left + red.outerWidth();
var paddingLeft = (redDistanceRight - distanceLeft) + extraPadding;
$('.intro section.white').css('padding-left', paddingLeft + 'px');
}
Update the answer below mine is a far better way to achieve what you're looking for. CSS is a much better responsive approach than excess JQuery.