Set div padding equal to an element's responsive height with jQuery - javascript
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!
Related
Javascript(addEventListener) not working on iOS
I added my code to Github, everything worked then I found out that it does not work below iOS 13. But in CodePen it clearly works. Here it is window.onload = function () { const target = document.querySelectorAll("[data-text-swap]"); let touchEvent = "ontouchstart" in window ? "touchstart" : "click"; for (let i = 0; i < target.length; i++) { target[i].addEventListener(touchEvent,function () { target[i].closest(".group") ?.querySelector(".toggle_cont").toggleAttribute("visible"); if (target[i].getAttribute("data-text-swap") == target[i].innerHTML) { target[i].innerHTML = target[i].getAttribute("data-text-original"); target[i].classList.remove("cgray"); } else { target[i].setAttribute("data-text-original", target[i].innerHTML); target[i].innerHTML = target[i].getAttribute("data-text-swap"); target[i].classList.add("cgray"); } },true ); } } a,abbr,acronym,address,applet,article,aside,audio,b,big,blockquote,body,canvas,caption,center,cite,code,dd,del,details,dfn,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,html,i,iframe,img,ins,kbd,label,legend,li,mark,menu,nav,object,ol,output,p,pre,q,ruby,s,samp,section,small,span,strike,strong,sub,summary,sup,table,tbody,td,tfoot,th,thead,time,tr,tt,u,ul,var,video{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline}:focus{outline:0}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:after,blockquote:before,q:after,q:before{content:'';content:none}table{border-collapse:collapse;border-spacing:0}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration,input[type=search]::-webkit-search-results-button,input[type=search]::-webkit-search-results-decoration{-webkit-appearance:none;-moz-appearance:none}input[type=search]{-webkit-appearance:none;-moz-appearance:none;-webkit-box-sizing:content-box;box-sizing:content-box}textarea{overflow:auto;vertical-align:top;resize:vertical}audio,canvas,video{display:inline-block;max-width:100%}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}a:focus{outline:thin dotted}a:active,a:hover{outline:0}img{border:0;-ms-interpolation-mode:bicubic}figure{margin:0}form{margin:0}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0;white-space:normal}button,input,select,textarea{font-size:100%;margin:0;vertical-align:baseline}button,input{line-height:normal}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}input[type=checkbox],input[type=radio]{-webkit-box-sizing:border-box;box-sizing:border-box;padding:0}input[type=search]{-webkit-appearance:textfield;-webkit-box-sizing:content-box;box-sizing:content-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}button,html,input,select,textarea{color:#222}::-moz-selection{background:#b3d4fc;text-shadow:none}::selection{background:#b3d4fc;text-shadow:none}img{vertical-align:middle}fieldset{border:0;margin:0;padding:0}textarea{resize:vertical}.chromeframe{margin:.2em 0;background:#ccc;color:#000;padding:.2em 0}a{text-decoration:none;color:#4b5a65}body{font-family:sans-serif;font-style:normal;font-weight:400;background-color:#f2f7fb;width:100%;height:100vh;margin:0;padding:0;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column}header{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;width:calc(100% - 30px);margin:26px auto 30px auto;max-width:1160px}.sidenav{display:none}.bigLogo{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start;-webkit-box-flex:1;-ms-flex:1;flex:1}.bigLogo img{width:341px;height:76px}.minLogo{display:none}.minLogo img{width:61px;height:60px}.link_list_open{display:none}.link_list{display:-webkit-box;display:-ms-flexbox;display:flex}.link_list ul{display:-webkit-box;display:-ms-flexbox;display:flex}.link_list ul li{color:#4b5a65;display:-webkit-box;display:-ms-flexbox;display:flex;margin-right:55px}.link_list ul li a{font-weight:500;font-size:17px;line-height:28px;color:#485a65;min-height:28px}.cgray{color:#bdbdbd!important}.cred{color:#ff5441!important}.dropbtn{width:41px;height:41px;background:#fff;border:0;-webkit-box-shadow:0 5px 10px rgba(82,91,99,.06);box-shadow:0 5px 10px rgba(82,91,99,.06);padding:0;border-radius:8px}.dropdown{position:relative;display:inline-block}.dropdownContent{display:none;position:absolute;min-width:41px;-webkit-box-shadow:0 5px 10px rgba(82,91,99,.06);box-shadow:0 5px 10px rgba(82,91,99,.06);z-index:1;border-radius:0 0 8px 8px}.dropbtn span{font-weight:700;font-size:17px;line-height:41px;color:#181818}.dropdownContent a{font-weight:700;font-size:17px;line-height:20px;color:#181818;width:41px;height:35px;text-decoration:none;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;margin-top:1px;-webkit-padding-before:5px;padding-block-start:5px;background:#fff}.dropdownContent a:hover{background-color:#ff5441;color:#fff}.dropdownContent a:last-child{border-radius:0 0 8px 8px}.dropdown:hover .dropdownContent{display:block}.dropdown:hover .dropbtn{border-radius:8px 8px 0 0;-webkit-box-shadow:0 0 10px rgba(82,91,99,.06);box-shadow:0 0 10px rgba(82,91,99,.06)}main{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-ms-flex-preferred-size:100%;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.main_title{font-weight:700;font-size:36px;line-height:50px;color:#181818;margin:0 0 30px}.group{background:#fff;-webkit-box-shadow:0 15px 35px rgba(82,91,99,.06);box-shadow:0 15px 35px rgba(82,91,99,.06);border-radius:25px;min-width:300px;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:distribute;justify-content:space-around;padding:30px;max-height:620px;min-height:490px}.group:first-child{margin-left:0}.group:last-child{margin-right:0}.about_group,.main_group{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between;-ms-flex-item-align:center;align-self:center;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-flow:row nowrap;flex-flow:row nowrap;width:calc(100% - 30px);max-width:1160px}.about_group{-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-flow:column nowrap;flex-flow:column nowrap;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.group_logo{display:-webkit-box;display:-ms-flexbox;display:flex;height:65px;width:240px;margin:0 auto 30px}.group_logo img{width:240px}.group_text{font-size:17px;line-height:30px;color:#64707a;width:270px;height:270px;-ms-flex-item-align:center;-ms-grid-row-align:center;align-self:center}.group_btn{background:-o-linear-gradient(left,#abb0c2 0,#b9c5e6 100%);background:-webkit-gradient(linear,left top, right top,color-stop(0, #abb0c2),to(#b9c5e6));background:linear-gradient(90deg,#abb0c2 0,#b9c5e6 100%);-webkit-box-shadow:0 10px 25px #cdd2e1;box-shadow:0 10px 25px #cdd2e1;border-radius:25px;max-width:250px;max-height:50px;margin:25px auto 0;width:-webkit-fit-content;width:-moz-fit-content;width:fit-content}.btn_text{font-weight:700;font-size:17px;line-height:26px;text-align:center;color:#fff;padding:14px 31.5px 10px;display:block}footer{margin:15px auto 0 auto;padding-bottom:30px}.copyright{font-size:14px;line-height:26px;color:#a5afb8}.light_group{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;-webkit-box-align:start;-ms-flex-align:start;align-items:flex-start;-ms-flex-item-align:start;align-self:flex-start;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column}.light_group:first-child{margin-right:23px}.light_group:last-child{-ms-flex-preferred-size:30%;flex-basis:30%;-webkit-box-flex:1;-ms-flex:1;flex:1}iframe{border:10px solid #fff;border-radius:25px;width:-webkit-fill-available;min-height:288px;max-width:658px;max-height:560px;height:50vh;margin-left:auto}.CallPhoto{margin:10px 30px 10px 0}.min_group{display:-webkit-box;display:-ms-flexbox;display:flex;min-width:155px;-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.min_group address,.min_group figcaption{font-size:17px;line-height:28px;color:#181818}.light_group .min_group:nth-child(2) a{text-decoration:underline;color:#5398ff}.numbers{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-flow:column wrap;flex-flow:column wrap}.members_img{display:-webkit-box;display:-ms-flexbox;display:flex;width:-webkit-fill-available;min-width:320px;max-width:1140px;border:10px solid #fff;-webkit-filter:drop-shadow(0 15px 35px rgba(82, 91, 99, .06));filter:drop-shadow(0 15px 35px rgba(82, 91, 99, .06));border-radius:25px}.logo_text{font-size:17px;line-height:28px;color:#4b5a65;max-width:960px;margin-top:30px}.logo_text span{font-weight:900}.btn_show{display:none;border:0;background-color:transparent;font-weight:700;font-size:16px;line-height:26px;text-align:center;color:#ff413e}#media all and (max-width:1130px) and (min-width:1060px){.group{padding:30px 20px}}#media all and (max-width:1060px) and (min-width:1022px){.group{padding-left:10px;padding-right:10px}}#media all and (min-width:1023px){.btn_show{max-height:0;margin:auto;opacity:0}.toggle_cont{-webkit-transition:0s;-o-transition:0s;transition:0s;max-height:400px!important;margin:0 auto!important;opacity:1!important}}#media all and (max-width:1022px){*{-webkit-transition:0s;-o-transition:0s;transition:0s}.toggle_cont{max-height:225px;-webkit-transition:all .5s linear;-o-transition:all .5s linear;transition:all .5s linear;overflow:hidden;}.toggle_cont *{max-height:-webkit-max-content!important;max-height:-moz-max-content!important;max-height:max-content!important}[visible]{-webkit-transition:all .5s linear;-o-transition:all .5s linear;transition:all .5s linear;max-height:0!important}main{min-height:initial!important}.group{width:75%;margin:15px auto;min-height:120px;padding:30px}.group:first-child{margin-top:0;margin-left:auto}.group:last-child{margin-right:auto}.group_btn{margin:25px auto 30px}.main_group,.about_group{-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-flow:column nowrap;flex-flow:column nowrap;width:100%}.group_text{width:auto;height:auto}.bigLogo,.link_list{display:none}.minLogo{display:-webkit-box;display:-ms-flexbox;display:flex}.link_list_open{display:-webkit-box;display:-ms-flexbox;display:flex;cursor:pointer}header{width:calc(75% + 60px);margin:12px auto 20px auto;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between}.link_list{display:none}.sidenav{height:100%;width:0;position:fixed;z-index:3;top:0;left:0;background-color:rgba(242,247,251,.7);-webkit-backdrop-filter:blur(25px);backdrop-filter:blur(25px);overflow-x:hidden;-webkit-transition:.5s;-o-transition:.5s;transition:.5s;display:block}.c100per{width:100%}.sidenav a{font-weight:700;font-size:30px;line-height:80px;padding:4px 8px 4px 15px;text-decoration:none;color:#181818;display:block;-webkit-transition:.3s;-o-transition:.3s;transition:.3s;width:-webkit-max-content;width:-moz-max-content;width:max-content}.sidenav a:hover{color:rgba(24,24,24,.5)}iframe{width:658px}.light_group:first-child{margin:0 auto 15px}.members_img{width:calc(75% + 50px)}.logo_text{width:calc(75% + 60px)}.btn_show{display:block;z-index:2}}#media all and (max-width:768px){.group{margin-bottom:0;min-width:230px;-ms-flex-pack:distribute;justify-content:space-around}.toggle_cont{max-height:405px}.about_group{width:100%}.members_img{border:0;-webkit-filter:drop-shadow(0 15px 35px rgba(82, 91, 99, .06));filter:drop-shadow(0 15px 35px rgba(82, 91, 99, .06));border-radius:0;margin:0;width:100%}.main_title{font-size:26px;margin-bottom:9px}.light_group:last-child{margin:0;width:100%}iframe{width:calc(75% + 40px);margin:0 auto;height:43.15vh}.btn_show::after{display:block}.light_group:first-child{width:calc(75% + 60px)}footer{padding-bottom:25px}}.arrow{border:solid #ff413e;border-width:0 3px 3px 0;display:inline-block;padding:3px;margin:5px}.up{-ms-transform:rotate(-135deg);transform:rotate(-135deg);-webkit-transform:rotate(-135deg);border-color:#bdbdbd;margin-bottom:-2px}.down{-ms-transform:rotate(45deg);transform:rotate(45deg);-webkit-transform:rotate(45deg);margin:3px}#media(max-height:802px) and (max-width:1023px){body{height:100%}}#media (max-height:861px) and (min-width:1024px) and (orientation:landscape){.gmin_height{min-height:430px}}#media (max-height:768px) and (min-width:1024px) and (orientation:landscape){.group_pad{padding-top:20px;padding-bottom:20px}} <section class="group gmin_height group_pad"> <figure class="group_logo"><img src="" alt="Group Logo" /></figure> <div class="toggle_cont" visible> <p class="group_text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Incidunt eveniet quae repellat dolores animi amet nemo quis tempora vero dignissimos fugit doloribus debitis sunt quod consequatur, quasi maiores sit mollitia. Porro facilis maxime unde esse et, labore magnam aliquam aspernatur. </p> <div class="group_btn">Coming soon </div> </div><button class="btn_show" data-text-swap='Roll up<i class="arrow up"></i>'>Learn more<i class="arrow down"></i></button> </section> <section class="group gmin_height group_pad"> <figure class="group_logo"><img src="" alt="Group Logo" /></figure> <div class="toggle_cont" visible> <p class="group_text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Incidunt eveniet quae repellat dolores animi amet nemo quis tempora vero dignissimos fugit doloribus debitis sunt quod consequatur, quasi maiores sit mollitia. Porro facilis maxime unde esse et, labore magnam aliquam aspernatur. </p> <div class="group_btn">Coming soon </div> </div><button class="btn_show" data-text-swap='Roll up<i class="arrow up"></i>'>Learn more<i class="arrow down"></i></button> </section> <section class="group gmin_height group_pad"> <figure class="group_logo"><img src="" alt="Group Logo" /></figure> <div class="toggle_cont" visible> <p class="group_text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Incidunt eveniet quae repellat dolores animi amet nemo quis tempora vero dignissimos fugit doloribus debitis sunt quod consequatur, quasi maiores sit mollitia. Porro facilis maxime unde esse et, labore magnam aliquam aspernatur. </p> <div class="group_btn">Coming soon </div> </div><button class="btn_show" data-text-swap='Roll up<i class="arrow up"></i>'>Learn more<i class="arrow down"></i></button> </section> By the way, the site must be opened on an iOS device below version 13 or here => https://appetize.io/demo?device=iphone5s&scale=75&orientation=portrait&osVersion=12.4 In full-screen mode it does not display correctly Tried to put cursor: pointer didn't help. And according to the terms of reference should not use any libraries, purely JavaScript. I would be very happy with any answer! Thank You!
The problem was iOS 12.5 didn't support my code. Had to change <button> in <checkbox> and used #checkbox: checked. The rest of the code in JavaScript works.
Accordion component hide on initial state with CSS + Javascript
So i have been trying to build this accordion component for a review section for a couple of days...I'm really new to javascript and have figured it out mostly except the review section that collapses out is being shown in the initial state so on a page reload you see the section expanded right away, and only is hidden when you click the expand arrow. I would rather it be hidden on the initial state so it only is shown after the user clicks the expand arrow. I have a div with the class="reviewsHide" as a wrapper and another div with the class="reviewsActive" as a wrapper. Its written in sass and any solution i try to come up with in targeting the wrapper with javascript doesn't apply its children class styles so it ends up not looking right. Inside the main container wrappers i have 3 more container sections each is its own container. with a couple of classes inside each of those containers. <div class="reviewsHide"> <div class="reviewsActive"> <div class="reviewsActive__top"> <button href="#" class="reviewsActive__top-smallTxt">Write A Review →</button> <span class="reviewsActive__top-largeTxt">Reviews(10)</span> <button href="#" class="reviewsActive__top-smallTxt">More Reviews →</button> </div> <div class="reviewsActive__bottomL"> <div class="reviewsActive__bottomL-title"> <img class="starSmall"src="img/main/StarRating.svg" alt="Star Rating"> Title </div> <p class="reviewsActive__bottomL-reviewP">   Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis, dolorem quae! Quidem officiis rerum nam, veritatis ullam, placeat est doloremque exercitationem, a quis sequi tempora blanditiis eligendi consequuntur. Ipsam a hic eligendi? Facilis vero fugit omnis ducimus inventore ipsam libero ad expedita numquam, ullam delectus ratione modi, atque esse veritatis. </p> </div> <div class="reviewsActive__bottomR"> <div class="reviewsActive__bottomR-title"> <img class="starSmall"src="img/main/StarRating.svg" alt="Star Rating"> Title </div> <p class="reviewsActive__bottomR-reviewP">   Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis, dolorem quae! Quidem officiis rerum nam, veritatis ullam, placeat est doloremque exercitationem, a quis sequi tempora blanditiis eligendi consequuntur. </p> </div> </div> </div> .reviewsHide.show { height: 15rem; display: none; } .reviewsActive { display: flex; flex-direction: row; flex-wrap: wrap; background-color: white; height: 22.5rem; font-family: 'Montserrat Alternates', sans-serif; &__top { display: flex; flex-direction: row; justify-content: space-evenly; align-items: center; height: 3rem; width: 100%; &-smallTxt { cursor: pointer; font-size: 1.05rem; } &-largeTxt { font-size: 2rem; } } &__bottomL { #include reviewsBottom; margin: auto 1rem .75rem 1rem; &-title { #include reviewsTitle; } &-reviewP { #include reviewsParagraph; } } &__bottomR { #include reviewsBottom; margin: 1rem 1rem .75rem auto; &-title { #include reviewsTitle; } &-reviewP { #include reviewsParagraph; } } } // Get the button, and when the user clicks on it, execute myFunction document.querySelector(".span").onclick = function() {myFunction()}; /* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */ function myFunction() { document.querySelector(".reviewsHide").classList.toggle("show"); /* This selector below is for the arrow animation to rotate on click */ document.querySelector(".span").classList.toggle("spanshow"); }
Re-wrote my javascript to this and its working as intended const reviewsOpen = () => { var expandArrow = document.querySelector(".span"); var hide = document.querySelector(".reviewsHide"); expandArrow.addEventListener('click', () => { hide.classList.toggle("reviewsHide"); expandArrow.classList.toggle("spanshow") }); } reviewsOpen();
How to close a menu bar when clicking outside of it [duplicate]
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
When Javascript Enable in Chrome site my JS is not working/ But when i disable JS its working, Why ? i want to on JS
My requirement is that I need to ON/Enable JavaScript on some site Okay, But when I keep JavaScript Enable in Chrome site my another JS (this PopUp on selection) is not working, But when I disable/Block all JS for the same site the Popup script is working, Why? Rather I want to on JS. Now I want to use this Popup script on a webpage, when all other JS is enabled, How to do it? But here my problem is when all other JS is enabled, This Popup is not working So Plz Any Body can solve my issue, many many advance thanks to them. My Popup Function Code is: const container2 = document.querySelector('#article_body'); const popupContainer = document.querySelector('.popupContainer'); // this method is added // It gives the text of HTML of selected text :) function getHTMLOfSelection () { var range; if (document.selection && document.selection.createRange) { range = document.selection.createRange(); return range.htmlText; } else if (window.getSelection) { var selection = window.getSelection(); if (selection.rangeCount > 0) { range = selection.getRangeAt(0); var clonedSelection = range.cloneContents(); var div = document.createElement('div'); div.appendChild(clonedSelection); return div.innerHTML; } else { return ''; } } else { return ''; } } container2.addEventListener('mouseup', (e) => { const selectedText = getHTMLOfSelection(); // First get the raw HTML text if (selectedText) { //selectedText.split("<").join("<"); // Now replacing the < so that browser don't render it //selectedText.split(">").join(">"); // Also replacing the > so that browser don't render it //console.log(selectedText); showPopup(selectedText); // using the 'xmp' tags around the text, to show2 the html as it is } }); popupContainer.addEventListener('click', (event) => { if (event.target.matches('.popupContainer')) { popupContainer.classList.remove('show2'); } }); function showPopup(selectedText) { // set the selected text as html inside popup2 element document.querySelector('.popup2').innerHTML = selectedText; popupContainer.classList.add('show2'); } .popupContainer { position: fixed; width: 100vw; height: 100vh; background: rgba(0, 0, 0, 0.7); top: 0; display: flex; opacity: 0; transition: opacity 0.2s ease; pointer-events: none; align-items: center; justify-content: center; color: red; z-index: 1; overflow: scroll; font-family: Kohinoor Devanagari; box-shadow: inset -17px -6px 20px 20px #0c3f41, 0 0 25px blue, 0 0 5px darkblue; } .show2 { opacity: 1; pointer-events: all; } .popup2 { background: #fff; padding: 10px; border-radius: 3px; box-shadow: 0 0 5px rgba(0, 0, 0, 0.3); width: 80%; transition: transform 0.4s cubic-bezier(.39,.575,.565,1.000); -webkit-transform: scale(.5);transform:scale(.5) } .show2 .popup2 { -webkit-transform: scale(1);transform:scale(1) } <div class="popupContainer"><div class="popup2"></div></div> <div id="article_body"> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Recusandae pariatur eos aperiam saepe, beatae necessitatibus exercitationem, nemo, sit provident possimus debitis modi eligendi repellat iure vitae perferendis? Recusandae accusamus placeat velit itaque quis fuga laudantium debitis, ab eaque voluptatum illo esse incidunt! Quia tempore explicabo sint laboriosam rerum nihil voluptates voluptatibus voluptate iure. Earum magnam blanditiis voluptates quod ex exercitationem reiciendis, iure qui ducimus similique impedit nemo est, quisquam facere id adipisci harum tenetur consequuntur illum saepe laudantium. Suscipit facilis corporis natus aperiam! Reprehenderit hic quia natus nisi similique quod fugiat, architecto autem deleniti unde commodi accusamus modi voluptate? </div> Any Body can solve my issue, many many advance thanks to them.
Dynamically set padding-left based on overlap width of two elements
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.