Dynamically set padding-left based on overlap width of two elements - javascript

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.

Related

Set div padding equal to an element's responsive height with jQuery

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!

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("&lt"); // Now replacing the < so that browser don't render it
//selectedText.split(">").join("&gt"); // 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.

Is it possible to set a max on how far a component can scroll horizontally before text is wrapped?

I'd like for users to be able scroll horizontally across text in a React component, but I'd like to still have some bounded width that's larger than the component's bounding rectangle. This way, I could just have regular paragraphs without worrying about any line breaking on-the-fly. I know I would need to set the overflow-x property to auto, but I'm not sure what to do past that. Thanks for the help!
Here would be my solution.
body {
width: 100%;
max-width: 800px;
margin: 30px auto;
}
.wrapper {
border: 1px solid #afafaf;
width: 100%;
overflow-x: scroll;
box-sizing: border-box;
}
.inner {
padding: 10px;
width: 130%;
}
<div class="wrapper">
<div class="inner">Lorem ipsum dolor sit amet consectetur adipisicing elit. Ex labore, provident dolorum repellendus earum aliquid voluptatem nobis odit. Deserunt corrupti repellendus voluptate harum quaerat adipisci aut sequi consequuntur voluptas cum?</div>
</div>

Switching Div's on Refresh

I have a div at the top of the page, middle, and bottom. When I refresh the page each time I would like the top and bottom divs to switch without affecting the middle div at all. Thanks in advance for any answers.
My jsfiddle
Code:
.top {
background: lightpink;
padding: 40px;
}
.content {
background: white;
}
.bottom {
background: lightblue;
padding: 40px;
}
<div class="top">
1
</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ullam fuga impedit, obcaecati, commodi dolores quasi odit numquam esse aliquid, alias natus doloribus nihil eius dicta eaque, nobis veritatis! Praesentium, laboriosam.
</div>
<div class="bottom">
2
</div>
It can be done using sessionStorage and cloning divs.
What this is doing is taking a copy of each div in the clone variables and then using a sessionStorage value to toggle between the states. If the sessionStorage value is 0 then it will do nothing but change the value, if it's 1 then it'll remove the divs and then add them in the new order from the cloned content.
var divOne = document.querySelector('.top');
var divTwo = document.querySelector('.bottom');
var divOneClone = document.querySelector('.top').outerHTML;
var divTwoClone = document.querySelector('.bottom').outerHTML;
var divContent = document.querySelector('.content');
if (sessionStorage.getItem('refreshState')) {
if (sessionStorage.getItem('refreshState') == 1) {
divOne.parentNode.removeChild(divOne);
divTwo.parentNode.removeChild(divTwo);
divContent.insertAdjacentHTML('beforebegin', divTwoClone);
divContent.insertAdjacentHTML('afterend', divOneClone);
sessionStorage.setItem('refreshState', 0);
} else {
sessionStorage.setItem('refreshState', 1);
}
} else {
sessionStorage.setItem('refreshState', 0);
}
Here's a working JS Fiddle example.

Read more link with pure JavaScript

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);
})
}

Categories