I want (setting - content) to be closed every time the user clicks on any part of the window except setting - content.
but not work this code: (document.querySelector('body').addEventListener('click', function(e){....})and signals an error.
How can I do this correctly?
var icon = document.getElementsByClassName("setting--icon");
var panel = document.getElementsByClassName('setting--content');
for (var i = 0; i < icon.length; i++) {
icon[i].onclick = function(){
var setClasses = !this.classList.contains('active');
setClass(icon, 'active', 'remove');
setClass(panel, 'active', 'remove');
if (setClasses) {
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("active");
}
}
}
function setClass(els, className, fnName) {
for (var i = 0; i < els.length; i++) {
els[i].classList[fnName](className);
}
}
document.querySelector('body').addEventListener('click', function(e){
if (!(event.target == 'setting--content')) { panel.classList.remove('active');
this.nextElementSibling.classList.remove("active");
}
})
.setting--icon{
border: 1px solid red;
width:20px;
height:20px;
}
.setting--content {
position: fixed;
left: 50%;
top: -150%;
width: 50%;
height:20px;
margin: 0 auto;
text-align: center;
transition: 0.3s;
min-height: 300px;
padding: 2rem;
transform: translateX(-50%);
border:1px solid green;
}
.setting--content.active {
top: 20%;
}
<form >
<div class="setting--icon">1</div>
<div class="setting--content">
<input type="text" name="address" id="address" placeholder="search …">
</div>
</form>
<div>
<div class="setting--icon">2</div>
<div class="setting--content">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Natus explicabo repellendus quos illo eaque vitae, nostrum id accusantium. Cum est fugiat animi molestiae dicta praesentium repellat ipsa iusto dolore perspiciatis? </p>
</div>
</div>
To check which element has clicked, you can use matches method on HTMLElement, in your body click handler you can use it like this:
event.target.matches('.setting--content');
In your snippet, you are toggling the .setting--content by clicking on .setting--icon, so you should check that target is not .setting--icon like this:
event.target.matches('.setting--icon');
in order to above checkings, you should also check that clicked item is not in the .setting--content, you can do it by storing the current active panel in a variable and by using of contains method, check that clicked item is part of the .setting--content or not. like this:
var icon = document.getElementsByClassName("setting--icon");
var panel = document.getElementsByClassName('setting--content');
var activePanel = null;
for (var i = 0; i < icon.length; i++) {
icon[i].onclick = function() {
var setClasses = !this.classList.contains('active');
setClass(icon, 'active', 'remove');
setClass(panel, 'active', 'remove');
if (setClasses) {
this.classList.toggle("active");
activePanel = this.nextElementSibling;
activePanel.classList.toggle("active");
}
}
}
function setClass(els, className, fnName) {
for (var i = 0; i < els.length; i++) {
els[i].classList[fnName](className);
}
}
document.querySelector('body').addEventListener('click', function(event) {
if (!event.target.matches('.setting--content') &&
!event.target.matches('.setting--icon') &&
activePanel && !activePanel.contains(event.target)) {
setClass(panel, 'active', 'remove');
setClass(icon, 'active', 'remove');
}
})
body {
min-height: 100vh;
}
.setting--icon {
border: 1px solid red;
width: 20px;
height: 20px;
}
.setting--content {
position: fixed;
left: 50%;
top: -200%;
width: 50%;
height: 20px;
margin: 0 auto;
text-align: center;
transition: 0.3s;
min-height: 300px;
padding: 2rem;
transform: translateX(-50%);
border: 1px solid green;
}
.setting--content.active {
top: 20%;
}
<form>
<div class="setting--icon">1</div>
<div class="setting--content">
<input type="text" name="address" id="address" placeholder="search …">
</div>
</form>
<div>
<div class="setting--icon">2</div>
<div class="setting--content">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Natus explicabo repellendus quos illo eaque vitae, nostrum id accusantium. Cum est fugiat animi molestiae dicta praesentium repellat ipsa iusto dolore perspiciatis? </p>
</div>
</div>
BTW, since your .setting--content has fixed display, in below example I added style body{ min-height: 100vh; } in order to prevent body collapssed. and also I changed top property on .setting--content from -150% to -200% to run snippet correctly in preview mode.
Related
Google uses a feedback feature that highlights the background color of content elements (ex:p, div, ul, h2, etc.) when the user mouses over a div to the right side of the content.
I believe the following CSS class is applied to the element to highlight its background:
.inline-feedback__highlight {
background: #d2e3fc;
-webkit-border-radius: .3125rem;
border-radius: .3125rem;
}
Using jQuery or JavaScript and CSS, I'd like to achieve the same result.
My Question
How can I identify what the closest element in <div id="content">...</div> is?
I was thinking some form of x,y coordinates and offset from the top of the content div.
My Code
$(function() {
let halfBtnHt = Math.ceil($('#track-button-div').height() / 2);
$('#track-container').on('mousemove', function(e) {
// console.log(e.offsetX, e.offsetY);
$('#track-button').css({
'transform': `translateX(0) translateY(${e.offsetY - halfBtnHt}px)`,
'visibility': 'visible',
})
}).on('mouseout', function(e) {
$('#track-button').css({
'visibility': 'hidden'
})
})
})
#content-container {
position: relative;
border: 1px solid black;
width: 500px;
height: auto;
margin: 100px auto;
}
#content {
padding: 2rem;
}
#track-container {
position: absolute;
text-align: center;
top: 0;
bottom: 0;
width: 64px;
right: -56px;
z-index: 1;
}
#track-button {
width: 42px;
height: 42px;
border-radius: 30px;
pointer-events: none !important;
}
#track-button-div {
visibility: hidden;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA==" crossorigin="anonymous" />
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content-container">
<div id="content">
<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam, iusto? Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur dolores earum esse eveniet libero minima pariatur repellat sed sunt ut?</div>
<pre class="prettyprint linenums prettyprinted">
<ol class="linenums">
<li class="L0">Hey</li>
</ol>
</pre>
<p>Blanditiis corporis ducimus laudantium nisi pariatur quasi repellat sunt, ut? Consequuntur dolores earum</p>
</div>
<div id="track-container">
<div id="track-button-div">
<button id="track-button" class="btn btn-outline-primary">
<i class="fas fa-quote-right"></i>
</button>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script src="track.js"></script>
</body>
</html>
Here's what Google's Feedback Feature Looks Like
Look at snippet below:
(function ($) {
'use strict';
$(function () {
var
namespace = 'mmdm',
//-----
mainElementID = '#__elements_container',
highlightClass = 'founded-element__highlight',
//-----
mainElement = $(mainElementID),
movableElementContainer = $('#__movable_element_container'),
movableElement = $('#__movable_element');
// some utility
function getTouch(event) {
var touch = event;
if (('ontouchstart' in document.documentElement) || navigator.maxTouchPoints > 0) {
touch = event.originalEvent.touches && event.originalEvent.touches.length ? event.originalEvent.touches[0] : event;
if (event.type === 'touchstart' || event.type === 'touchmove') {
touch = event.targetTouches[0] || event.changedTouches[0];
}
}
return touch;
}
// define function(s)
function removeHighlightClass() {
mainElement.find('*').removeClass(highlightClass);
}
function findElementsWithSameYNHighlightIt(e) {
var x, y, meOffset, el;
meOffset = mainElement.offset();
x = (e.pageX - meOffset.left) / 2;
y = e.pageY - $(window).scrollTop();
el = document.elementFromPoint(x, y);
if (!$(el).is(mainElement) && $(el).closest(mainElementID).length) {
$(el).addClass(highlightClass);
}
}
function showMovableElement() {
movableElement.addClass('show');
}
function hideMovableElement() {
movableElement.removeClass('show');
}
function moveMovableElement(e) {
var y, mecTop = movableElementContainer.offset().top;
y = e.pageY;
// bound move to the main movable container
if (y >= mecTop && y <= (mecTop + movableElementContainer.outerHeight())) {
movableElement.css({
'top': y - mecTop - (movableElement.outerHeight() / 2)
});
}
removeHighlightClass();
}
// attach event(s)
movableElementContainer
.on('mousemove.' + namespace + ' touchmove.' + namespace + ' mouseenter.' + namespace + ' touchstart.' + namespace, function (e) {
if (!e.defaultPrevented && e.cancelable) {
e.preventDefault();
}
//-----
var touch = getTouch(e);
showMovableElement();
moveMovableElement(touch);
findElementsWithSameYNHighlightIt(touch);
}).on('mouseleave.' + namespace + ' touchend.' + namespace, function (e) {
if (!e.defaultPrevented && e.cancelable) {
e.preventDefault();
}
//-----
hideMovableElement();
removeHighlightClass();
});
});
})(jQuery);
* {
box-sizing: border-box;
}
#__elements_main_container {
display: flex;
}
#__elements_container {
width: 500px;
}
#__movable_element_container {
position: relative;
width: 40px;
}
#__movable_element_container::after {
content: '';
position: absolute;
top: 0;
left: 50%;
width: 1px;
height: 100%;
background-color: #ccc;
transform: translate(-50%);
z-index: 1;
}
#__movable_element {
position: absolute;
display: none;
align-items: center;
justify-content: center;
left: 50%;
width: 40px;
height: 40px;
text-align: center;
border-radius: 50rem;
border: 1px solid #ccc;
background-color: #fff;
box-shadow: 0 2px 5px rgba(0, 0, 0, .26);
transform: translate(-50%);
z-index: 2;
}
#__movable_element.show {
display: flex;
}
.founded-element__highlight {
background-color: #cecdff;
border-radius: 3px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="__elements_main_container">
<div id="__elements_container">
<h1>
A heading tag!
</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<ul>
<li>First list item</li>
<li>Second list item</li>
</ul>
</div>
<div id="__movable_element_container">
<i id="__movable_element" class="fa fa-quote-right"></i>
</div>
</div>
Please don't judge the code quality, I made it just for the sake of testing and making it do what you initially asked about selecting the closest element.
Check this sandbox with a working example
The key here is the usage of elementFromPoint function, the sandbox should just give a general idea and you can tailor it to your needs!
I have a span defined, to which I am occasionally adding text and I am trying to get it to scroll to the bottom of the "box" but without success.
I have the span defined as:
<tr>
<td style="height:130px; border: 1px solid black;">
<div class="scrollable">
<span id="infoWindow"></span>
</div>
</td>
</tr>
With
div.scrollable
{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: auto;
}
And I am adding to it as follows:
document.getElementById("infoWindow").innerHTML+="Just some blurb<hr>";
var objDiv = document.getElementById("infoWindow");
I have tried two different approaches:
objDiv.scrollTop = objDiv.scrollHeight - objDiv.clientHeight;
and
objDiv.scrollTop = objDiv.scrollHeight;
But neither work. What am I doing wrong? Many thanks!
scrollHeight and clientHeight are properties which are calculated when DOM has been fully painted. You should subscribe to event DOMContentLoaded to be sure the calculations are done.
There is a function scrollIntoView which you can use on any element which does exactly the name suggests. MDN - scrollIntoView. You can also define some options for scrolling like smoothness and position where to scroll exactly on element.
Here is an example I wrote to test this.
Keep in mind that scrollIntoView triggered by code example will impact SO scroll behavior.
const paragraphs = ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliter enim nosmet ipsos nosse non possumus. Sin dicit obscurari quaedam nec apparere, quia valde parva sint, nos quoque concedimus; Quis autem de ipso sapiente aliter existimat, quin, etiam cum decreverit esse moriendum, tamen discessu a suis atque ipsa relinquenda luce moveatur? Duo Reges: constructio interrete. Quem enim ardorem studii censetis fuisse in Archimede, qui dum in pulvere quaedam describit attentius, ne patriam quidem captam esse senserit? Id quaeris, inquam, in quo, utrum respondero, verses te huc atque illuc necesse est.',
'Nec vero sum nescius esse utilitatem in historia, non modo voluptatem. Hanc in motu voluptatem -sic enim has suaves et quasi dulces voluptates appellat-interdum ita extenuat, ut M. Hunc ipsum Zenonis aiunt esse finem declarantem illud, quod a te dictum est, convenienter naturae vivere. Suo enim quisque studio maxime ducitur. Manebit ergo amicitia tam diu, quam diu sequetur utilitas, et, si utilitas amicitiam constituet, tollet eadem.',
'Partim cursu et peragratione laetantur, congregatione aliae coetum quodam modo civitatis imitantur; Hic nihil fuit, quod quaereremus. Stoici restant, ei quidem non unam aliquam aut alteram rem a nobis, sed totam ad se nostram philosophiam transtulerunt; Deinde disputat, quod cuiusque generis animantium statui deceat extremum. Tibi hoc incredibile, quod beatissimum. Sed haec ab Antiocho, familiari nostro, dicuntur multo melius et fortius, quam a Stasea dicebantur. Quid enim necesse est, tamquam meretricem in matronarum coetum, sic voluptatem in virtutum concilium adducere? Ne vitationem quidem doloris ipsam per se quisquam in rebus expetendis putavit, nisi etiam evitare posset.'
];
const container = document.getElementById('infoWindow');
const paragraphElements = paragraphs.map((paragraphText, index) => {
const newParagraph = document.createElement('p');
newParagraph.innerHTML = paragraphText;
newParagraph.style.animationDelay = `${.8 * index + 1}s`;
return newParagraph;
});
const demostrateScrolling = () => {
const scroller = document.getElementById('scroller');
const scrollerOptions = {
behavior: 'smooth',
block: "start",
inline: "nearest"
};
scroller.addEventListener('click', () => {
container.querySelector('p:last-child').scrollIntoView(scrollerOptions);
});
paragraphElements.map(p => {
container.appendChild(p);
});
}
document.addEventListener('DOMContentLoaded', demostrateScrolling);
body {
font-family: 'Tahoma';
}
#infoWindow {
height: 200px;
overflow-y: auto;
margin: 10px;
}
#infoWindow p {
padding: 10px;
margin: 10px;
background-color: navy;
color: white;
border-radius: 5px;
animation-name: FadeIn;
animation-duration: .4s;
animation-fill-mode: backwards;
}
#keyframes FadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
#scroller {
width: auto;
background-color: lightblue;
border-radius: 24px;
padding: 5px;
margin: 5px;
font-size: 10px;
cursor: pointer;
}
<h2>Scroll To Bottom</h2>
<div id="infoWindow"></div>
<span id="scroller">Scroll to bottom</span>
refer this https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop
scrolling is applicable only to scrollable elements
var i= 0;
while(i<10){
document.getElementById("infoWindow").innerHTML+="Just some blurb<hr>";
i++;
}
//get the total height of your element
var bottomPosition = document.getElementById("infoWindow").offsetHeight;
//set scroll of container element
document.querySelector(".scrollable").scrollTop = bottomPosition;
div.scrollable
{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: auto;
}
/* height is no defined for inline-elements so make span inline-block or block*/
#infoWindow{
display:inline-block;
}
<table>
<tr>
<td style="height:130px; border: 1px solid black;">
<div class="scrollable">
<!-- added style for span element -->
<span id="infoWindow"></span>
</div>
</td>
</tr>
</table>
Goal: Attempting to incorporate an expanding image grid into my site, with 3 columns and 4 rows. I am working with an area of 810w x 1050h.
Issues: I can't seem to get the 3 x 4 grid to render correctly. You can see what I mean by this here: http://rthhockey.com/coaching2 I've played minimum/maximum heights to no avail.
Things I have tried: I have distributed each link by 33.3333....% Nothing seems to be working. I've been playing with the code for about 3 days now and I don't want to make things worse. I'm sure one of you guys can catch what I'm missing fairly quickly.
This is the CodePen where I found this grid: https://codepen.io/DanBoulet/pen/YXQBbZ
Any and all assistance would be greatly appreciated. Thanks for your time.
CSS
body {
background-color: #fff;
color: #ffffff;
font-family: open sans;
font-size: 100%;
font-weight: 400;
line-height: 1.5;
margin: 0 auto;
max-width: 100%;
height: 1050px;
max-height: 1050px;
overflow-y: scroll;
padding: 5px;
}
.expanding-grid {
position: relative;
width: 100%;
max-width: 100%;
}
.expanding-grid .links {
display: block;
margin: 0 -1em;
overflow: hidden;
padding: 5px;
}
.expanding-grid .links > li {
box-sizing: border-box;
float: left;
padding: 1em;
}
.expanding-grid .links > li a {
background: #ff2200;
color: #fff;
display: block;
font-size: 24px;
line-height: 1;
padding: 25% 1em;
position: relative;
width: 250px;
height: 150px;
text-align: center;
text-decoration: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.expanding-grid .links > li a:hover {
background: #ffb733;
}
.expanding-grid .links > li a.active {
background: #cc8400;
}
.expanding-grid .links > li a.active:after {
background-color: transparent;
border-bottom: 0.375em solid #888;
border-left: 0.375em solid transparent;
border-right: 0.375em solid transparent;
bottom: -0.5em;
content: '';
height: 0;
left: 50%;
margin-left: -0.375em;
position: absolute;
width: 0;
}
#media only screen and (max-width: 810px) {
.expanding-grid .links > li {
width: 50%;
}
.expanding-grid .links > li:nth-of-type(2n+1) {
clear: left;
}
}
#media only screen and (min-width: 40em) and (max-width: 810px) {
.expanding-grid .links > li {
width: 33.3333333333%;
}
.expanding-grid .links > li:nth-of-type(3n+1) {
clear: left;
}
}
#media only screen and (min-width: 810px) {
.expanding-grid .links > li {
width: 33.3333333333%;
}
.expanding-grid .links > li:nth-of-type(4n+1) {
clear: left;
}
}
.expanding-grid .spacer {
background-color: #ff2200;
clear: both;
display: block;
margin: 0 1em;
}
.expanding-grid .expanding-container {
clear: both;
display: none;
overflow: hidden;
width: 100%;
}
.expanding-grid .expanding-container.expanded, .expanding-grid .expanding-container:target {
display: block;
}
.expanding-grid .hentry {
background: #494949;
box-sizing: border-box;
clear: both;
color: #fff;
min-height: 4em;
overflow: hidden;
padding: 1em;
width: 100%;
}
.expanding-grid .hentry .entry-image {
box-sizing: border-box;
float: right;
margin-left: 1em;
padding: 0.25em 0 0.52em 1em;
text-align: center;
width: 50%;
}
.expanding-grid .hentry .entry-title {
font-size: 28px;
}
.expanding-grid .close-button {
background: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyMCIgaGVpZ2h0PSIyMCIgdmlld0JveD0iMCAwIDIwIDIwIj48cGF0aCBzdHJva2U9IiNmZmYiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLW1pdGVybGltaXQ9IjEwIiBkPSJNLjcuN2wxOCAxOG0tMTggMGwxOC0xOCIvPjwvc3ZnPg==) no-repeat scroll 50% 50% transparent;
color: #fff;
display: inline-block;
height: 20px;
line-height: 1;
overflow: hidden;
padding: 1.5em 2em;
text-decoration: none;
text-indent: 5em;
white-space: nowrap;
width: 20px;
will-change: opacity;
z-index: 5;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.expanding-grid .close-button.active {
transition: opacity 0.2s;
}
.expanding-grid .close-button:hover {
opacity: 0.5;
}
.img-placeholder {
background: #ffffff;
color: #fff;
font-size: 4em;
font-weight: 300;
line-height: 1;
width: 400px;
height: 350px;
padding: 5px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
HTML
<div class="expanding-grid">
<ul class="links">
<li>Jackson 5</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
</ul>
<div id="section1" class="expanding-container">
<article class="hentry">
<h1 class="entry-title">Jackson 5</h1>
<div class="entry-image"><div class="img-placeholder"><img src="https://i.imgur.com/Pa3wzWI.png?1"></div></div>
<p>- 3 Skaters Run This Drill At Once<br>- F1 Skates Top Of Circle And Takes Shot On Goal<br>- F2 Skates Full Circle Without Puck<br>- F3 Skates Inside/Out Pattern Around Face-Off Dot With Puck, Breaks On Goal For Shot<br>- F1 Picks Up Puck Below Far Circle, Matches Timing Of F2 Through Neutral Zone And Dishes Pass To F2<br>-F2 Breaks In On Goal For Shot While F1 Crashes Net For Rebound</p>
</article>
</div>
<div id="section2" class="expanding-container">
<article class="hentry">
<h1 class="entry-title">Title</h1>
<div class="entry-image"><div class="img-placeholder">2</div></div>
<p>- 3 Skaters Run This Drill At Once<br>- F1 Skates Top Of Circle And Takes Shot On Goal<br>- F2 Skates Full Circle Without Puck</p>
</article>
</div>
<div id="section3" class="expanding-container">
<article class="hentry">
<h1 class="entry-title">Title</h1>
<div class="entry-image"><div class="img-placeholder">3</div></div>
<p>Description. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nostrum consequatur, culpa voluptate distinctio iure! Error saepe cumque molestiae deserunt nemo autem non amet, aliquam vitae nulla sit praesentium unde iusto.</p>
</article>
</div>
<div id="section4" class="expanding-container">
<article class="hentry">
<h1 class="entry-title">Title</h1>
<div class="entry-image"><div class="img-placeholder">4</div></div>
<p>Description. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati veniam aliquam eos eius blanditiis, facilis minus quod nostrum. Dolores recusandae doloremque quam consequatur consequuntur accusantium quos possimus inventore ratione reiciendis!</p>
</article>
</div>
<div id="section5" class="expanding-container">
<article class="hentry">
<h1 class="entry-title">Title</h1>
<div class="entry-image"><div class="img-placeholder">5</div></div>
<p>Description. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nostrum consequatur, culpa voluptate distinctio iure! Error saepe cumque molestiae deserunt nemo autem non amet, aliquam vitae nulla sit praesentium unde iusto.</p>
</article>
</div>
<div id="section6" class="expanding-container">
<article class="hentry">
<h1 class="entry-title">Title</h1>
<div class="entry-image"><div class="img-placeholder">6</div></div>
<p>Description. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati veniam aliquam eos eius blanditiis, facilis minus quod nostrum. Dolores recusandae doloremque quam consequatur consequuntur accusantium quos possimus inventore ratione reiciendis!</p>
</article>
</div>
<div id="section7" class="expanding-container">
<article class="hentry">
<h1 class="entry-title">Title</h1>
<div class="entry-image"><div class="img-placeholder">7</div></div>
<p>Description. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nostrum consequatur, culpa voluptate distinctio iure! Error saepe cumque molestiae deserunt nemo autem non amet, aliquam vitae nulla sit praesentium unde iusto.</p>
</article>
</div>
<div id="section8" class="expanding-container">
<article class="hentry">
<h1 class="entry-title">Title</h1>
<div class="entry-image"><div class="img-placeholder">8</div></div>
<p>Description. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati veniam aliquam eos eius blanditiis, facilis minus quod nostrum. Dolores recusandae doloremque quam consequatur consequuntur accusantium quos possimus inventore ratione reiciendis!</p>
</article>
</div>
<div id="section9" class="expanding-container">
<article class="hentry">
<h1 class="entry-title">Title</h1>
<div class="entry-image"><div class="img-placeholder">9</div></div>
<p>Description. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nostrum consequatur, culpa voluptate distinctio iure! Error saepe cumque molestiae deserunt nemo autem non amet, aliquam vitae nulla sit praesentium unde iusto.</p>
</article>
</div>
<div id="section10" class="expanding-container">
<article class="hentry">
<h1 class="entry-title">Title</h1>
<div class="entry-image"><div class="img-placeholder">10</div></div>
<p>Description. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati veniam aliquam eos eius blanditiis, facilis minus quod nostrum. Dolores recusandae doloremque quam consequatur consequuntur accusantium quos possimus inventore ratione reiciendis!</p>
</article>
</div>
<div id="section11" class="expanding-container">
<article class="hentry">
<h1 class="entry-title">Title</h1>
<div class="entry-image"><div class="img-placeholder">11</div></div>
<p>Description. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nostrum consequatur, culpa voluptate distinctio iure! Error saepe cumque molestiae deserunt nemo autem non amet, aliquam vitae nulla sit praesentium unde iusto.</p>
</article>
</div>
<div id="section12" class="expanding-container">
<article class="hentry">
<h1 class="entry-title">Title</h1>
<div class="entry-image"><div class="img-placeholder">12</div></div>
<p>Description. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati veniam aliquam eos eius blanditiis, facilis minus quod nostrum. Dolores recusandae doloremque quam consequatur consequuntur accusantium quos possimus inventore ratione reiciendis!</p>
</article>
</div>
</div>
Script
var getLastSiblingInRow = function (element) {
var candidate = element,
elementTop = element.offsetTop;
while (candidate.nextElementSibling !== null) {
if (candidate.nextElementSibling.offsetTop > elementTop) {
return candidate;
}
candidate = candidate.nextElementSibling;
}
return candidate;
};
var calculatePageScrollDistance = function (top, bottom) {
var windowScrollDistance = $(window).scrollTop(),
windowHeight = $(window).height(),
scrollDistanceToTop,
scrollDistanceToBottom;
if (windowScrollDistance >= top) {
return top - windowScrollDistance;
}
else if ((windowScrollDistance + windowHeight) >= bottom) {
return 0;
}
else {
scrollDistanceToTop = top - windowScrollDistance;
// Find the distance we need to scroll to reveal the entire section.
scrollDistanceToBottom = bottom - (windowScrollDistance + windowHeight);
return Math.min(scrollDistanceToTop, scrollDistanceToBottom);
}
};
var expandingGrid = function (context, options) {
var defaults = {
animationDuration: 250,
linksSelector: '.links a',
expandingAreaSelector: '.expanding-container',
closeButtonMarkup: 'Close',
spacerMarkup: '<span class="spacer" aria-hidden="true"/>',
elementActiveClass: 'active',
elementExpandedClass: 'expanded',
onExpandBefore: false,
onExpandAfter: false
};
var settings = $.extend({}, defaults, options);
var isExpanded = false;
var activeLink = false;
var activeExpandedArea = false;
var activeExpandedAreaTop = false;
var activeExpandedAreaHeight = false;
var lastItemInActiveRow = false;
var activeRowChanged = false;
var checkExpandedAreaResize = false;
var $links = $(settings.linksSelector, context);
var $expandingAreas = $(settings.expandingAreaSelector, context);
var $closeButton = $(settings.closeButtonMarkup);
var $spacer = $(settings.spacerMarkup);
var $secondarySpacer = $spacer.clone();
var scrollSectionIntoView = function (top, bottom, duration, callback) {
var animate;
var scroll = 0;
var distance = calculatePageScrollDistance(top, bottom);
var windowScrollDistance = $(window).scrollTop();
var timeLeft;
duration = (typeof duration === 'undefined') ? settings.animationDuration : duration;
timeLeft = duration;
var start = new Date().getTime();
var last = start;
var tick = function() {
timeLeft = Math.max(duration - (new Date() - start), 0);
var x = (timeLeft === 0 || distance === 0) ? 0 : ((new Date() - last) / timeLeft * distance);
var diff = (distance > 0 ? Math.min(x, distance) : Math.max(x, distance));
distance = distance - diff;
scroll += diff;
window.scrollTo(0, windowScrollDistance + scroll);
last = new Date().getTime();
if (last - start <= duration) {
animate = (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
}
else {
if (typeof callback === 'function') {
callback();
}
}
};
tick();
};
$links.each(function () {
var $this = $(this);
var targetId = $this.attr('href').match(/#([^\?]+)/)[1];
var target = document.getElementById(targetId);
if (target) {
$this.click(function (event) {
var clickedLink = this;
var scrollTargetOffset;
var closeButtonAnimationDelay;
event.preventDefault();
// Is this link already expanded?
if (isExpanded && activeLink === clickedLink) {
$closeButton.click();
}
else {
$links.removeClass(settings.elementActiveClass).filter($this).addClass(settings.elementActiveClass).parent('li').each(function () {
var lastSibling = getLastSiblingInRow(this);
activeRowChanged = lastSibling !== lastItemInActiveRow;
if (activeRowChanged) {
lastItemInActiveRow = lastSibling;
}
if (isExpanded && activeRowChanged) {
$secondarySpacer.height($spacer.height());
$spacer.height(0).replaceWith($secondarySpacer);
}
$(lastItemInActiveRow).after($spacer);
});
if (isExpanded && activeRowChanged) {
$secondarySpacer.animate({height: 0}, settings.animationDuration, function () {
$(this).detach();
});
$closeButton.removeClass(settings.elementActiveClass).hide();
}
scrollTargetOffset = ($secondarySpacer.position().top < $spacer.position().top ? $secondarySpacer.height() : 0);
activeExpandedAreaTop = ($spacer.position().top - scrollTargetOffset);
$expandingAreas.removeClass(settings.elementExpandedClass).hide().filter(target).each(function () {
var $this = $(this);
var autoHeight = $this.height();
var autoOuterHeight = $this.outerHeight();
var initialHeight = (isExpanded && activeExpandedAreaHeight && (activeRowChanged === false)) ? activeExpandedAreaHeight : 0;
stopExpandedAreaMonitor();
$spacer.animate({height: autoHeight + 'px'}, settings.animationDuration);
$this.css({
height: initialHeight + 'px',
position: 'absolute',
left: 0,
top: $spacer.position().top + 'px'
}).show(0, function () {
if (typeof settings.onExpandBefore === 'function') {
settings.onExpandBefore.call(this);
}
}).animate({
height: autoHeight + 'px',
top: activeExpandedAreaTop + 'px'
}, settings.animationDuration, function () {
$this.css({height: 'auto'}).addClass(settings.elementExpandedClass);
activeExpandedAreaHeight = $this.height();
checkExpandedAreaResize = setInterval(function () {
var activeExpandedAreaNewHeight = $this.height();
if (activeExpandedAreaNewHeight !== activeExpandedAreaHeight) {
activeExpandedAreaHeight = activeExpandedAreaNewHeight;
syncExpandedAreaWithSpacer();
}
}, 1000);
if (typeof settings.onExpandAfter === 'function') {
settings.onExpandAfter.call(this);
}
});
var scrollTargetTop = $(clickedLink).offset().top - scrollTargetOffset;
var scrollTargetBottom = $this.offset().top + autoOuterHeight + 20 - scrollTargetOffset;
scrollSectionIntoView(scrollTargetTop, scrollTargetBottom);
});
closeButtonAnimationDelay = (isExpanded && activeRowChanged && ($this.parent().index() > $(activeLink).parent().index())) ? settings.animationDuration : (settings.animationDuration / 4);
$closeButton.css({
position: 'absolute',
right: 0,
top: activeExpandedAreaTop + 'px'
}).delay(closeButtonAnimationDelay).fadeIn(settings.animationDuration, function () {
$(this).addClass(settings.elementActiveClass);
});
activeLink = this;
activeExpandedArea = target;
isExpanded = true;
}
});
}
});
$closeButton.appendTo(context).hide().click(function (event) {
var $activeLink = $(activeLink);
var activeLinkTopOffset = $activeLink.offset().top;
var activeLinkBottomOffset = activeLinkTopOffset + $activeLink.outerHeight();
event.preventDefault();
$links.removeClass(settings.elementActiveClass);
$expandingAreas.slideUp(settings.animationDuration).removeClass(settings.elementExpandedClass);
$closeButton.removeClass('active').hide();
$spacer.animate({height: 0}, settings.animationDuration, function () {
$spacer.detach();
});
scrollSectionIntoView(activeLinkTopOffset, activeLinkBottomOffset);
stopExpandedAreaMonitor();
isExpanded = false;
activeLink = false;
activeExpandedArea = false;
});
var stopExpandedAreaMonitor = function () {
if (checkExpandedAreaResize) {
clearInterval(checkExpandedAreaResize);
}
};
var syncExpandedAreaWithSpacer = function () {
if (activeExpandedArea && isExpanded) {
$spacer.height($(activeExpandedArea).height());
activeExpandedAreaTop = $spacer.position().top;
$closeButton.add(activeExpandedArea).css({top: activeExpandedAreaTop + 'px'});
}
};
var positionSpacer = function () {
var lastSibling;
if (activeLink && lastItemInActiveRow && isExpanded) {
$spacer.detach();
lastSibling = getLastSiblingInRow($(activeLink).parent()[0]);
if (lastItemInActiveRow !== lastSibling) {
console.log(lastSibling);
lastItemInActiveRow = lastSibling;
}
$(lastItemInActiveRow).after($spacer);
}
};
$(window).resize(function () {
if (isExpanded) {
positionSpacer();
syncExpandedAreaWithSpacer();
}
});
};
// Create the jQuery plugin.
$.fn.expandingGrid = function (options) {
return this.each(function () {
expandingGrid(this, options);
});
};
})(jQuery, window, document);
$(document).ready(function () {
$('.expanding-grid').expandingGrid();
});
This can be done very easily using CSS grid. W3 Schools has a great, easy to follow example that can be found here.
Here is a 3x4 responsive grid using using the linked code:
.grid-container {
max-width: 810px;
max-height: 1050px;
display: grid;
grid-template-columns: auto auto auto auto;
background-color: #2196F3;
padding: 10px;
}
.grid-item {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
font-size: 30px;
text-align: center;
}
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
<div class="grid-item">7</div>
<div class="grid-item">8</div>
<div class="grid-item">9</div>
<div class="grid-item">10</div>
<div class="grid-item">11</div>
<div class="grid-item">12</div>
</div>
I've set the grid container to allow a max width of 810 px and a max height of 1050 px, as you specified in your post. Just add your content for each grid item inside the corresponding div tag, and you're set!
My navbar have a title named LOGO ABCD,
I try to set when scrolling down change colour by adding and removing class,
but no idea why not work
LOGO ABCD
A
B
C
D
nav.navbar {
transition: 0.5s;
}
nav.navbar.navbar-default.navbar-fixed-top.navbar-top {
background-color: Black;
}
nav.navbar.navbar-default.navbar-fixed-top.navbar-top a {
color : white;
}
nav.navbar.navbar-default.navbar-fixed-top.navbar-top a:hover {
color : yellow;
}
$(window).scroll(function(evt){
if ($(window).scrollTop()>0)
$(".navbar").removeClass("navbar-top");
else
$(".navbar").addClass("navbar-top");
});
.PJ_title{color:grey;}
.PJ_color{color:red;}
$(window).scroll(function(evt){
if ($(window).scrollTop()>300)
$(".PJ_title").removeClass("PJ_color");
else
$(".PJ_title").addClass("PJ_color");
});
I test and "Test Title" has changed color successfully.
You can run lower snippet and scroll down and see change color. What's the problem?
$(window).scroll(function(evt){
if ($(window).scrollTop()>0)
$(".navbar").removeClass("navbar-top");
else
$(".navbar").addClass("navbar-top");
});
$(window).scroll(function(evt){
if ($(window).scrollTop()>300)
$(".PJ_title").removeClass("PJ_color");
else
$(".PJ_title").addClass("PJ_color");
});
nav.navbar {
transition: 0.5s;
}
nav.navbar.navbar-default.navbar-fixed-top.navbar-top {
background-color: Black;
}
nav.navbar.navbar-default.navbar-fixed-top.navbar-top a {
color : white;
}
nav.navbar.navbar-default.navbar-fixed-top.navbar-top a:hover {
color : yellow;
}
.PJ_title{color:grey;}
.PJ_color{color:red;}
.PJ_title{ position: fixed; }
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body style='height: 1000px'>
<nav class='navbar navbar-default navbar-fixed-top navbar-top'>
<a>Test</a>
</nav>
<h1 class='PJ_title'>Test Title</h1>
</body>
</html>
Here's how you can do this. In the scroll function use, this.scrollY. Based on the value, add or remove classes as you see fit.
$(document).ready(function() {
$(window).scroll(function(evt) {
var scrollPos = this.scrollY;
if (scrollPos > 200) {
$(".navbar").removeClass("navbar-green");
$(".navbar").addClass("navbar-blue");
} else {
$(".navbar").addClass("navbar-green");
$(".navbar").removeClass("navbar-blue");
}
});
});
nav.navbar {
background-color: #ccc;
transition: all 0.5s ease-out;
}
nav.navbar-fixed-top {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
.extra-long {
height: 200vw;
}
nav.navbar-green {
background-color: green;
}
nav.navbar-blue {
background-color: blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="extra-long">
<nav class="navbar navbar-fixed-top">
<p>LOGO ABCD</p>
<p>A</p>
</nav>
</div>
Here's a version of your code cleaned up that works. You'll have to change the color as needed:
const w = $(window);
const header = $('#main-header');
w.on('scroll', function() {
if(w.scrollTop() > 0) {
header.addClass('header-secondary');
} else {
header.removeClass('header-secondary');
}
});
html {
height: 100%;
}
body {
margin: 0;
font-family: sans-serif;
height: 100%;
}
header {
width: 100%;
display: flex;
position: fixed;
align-items: center;
background-color: #ccc;
height: 50px;
transition: background-color ease .3s;
}
header nav {
margin-left: auto;
padding-right: 15px;
}
header nav a {
text-decoration: none;
}
#logo {
font-weight: 700;
padding-left: 15px;
}
.header-secondary {
background-color: darkblue;
color: #fff;
}
.header-secondary nav a {
color: #fff;
}
main {
padding: 65px 15px 0;
background-color: salmon;
height: 200%;
}
main p {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header id="main-header">
<p id="logo">LOGO ABCD</p>
<nav>
item
item
item
</nav>
</header>
<main>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Officiis adipisci totam odit natus voluptates ducimus impedit provident eum quia asperiores vitae neque ullam deserunt enim dolore minima, cum, perferendis et laborum. Magni, odit. Ducimus reiciendis illo assumenda dignissimos? Quidem eligendi molestiae atque mollitia, exercitationem officia. Debitis incidunt voluptas explicabo aliquam.</p>
</main>
I'm using cycle2 plugin for my carousel and I wrote a basic function to start slide images on hover but there is something that I couldn't achieve is when I left my cursor from area carousel must return first image how to do that ?
$('.img-area').cycle({
fx: 'none',
speed: 750,
timeout: 100
}).cycle("pause");
$(".otel-list").hover(function() {
$(".img-area").cycle("resume");
}, function() {
$(".img-area").cycle("pause");
});
.otel-list {
width: 700px;
background: #f0f0f0;
border-bottom: 5px solid #ccc;
}
.otel-list:after,
.otel-list-:before {
content: "";
display: table;
clear: both;
}
.img-area {
width: 33%;
float: left;
position: relative;
}
.img-area img {
width: 100%;
position: absolute;
top: 0;
left: 0;
}
.content-area {
float: right;
width: 66%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.cycle2/2.1.6/jquery.cycle2.js"></script>
<div class="otel-list">
<div class="img-area">
<img src="http://malsup.github.io/images/p1.jpg" />
<img src="http://malsup.github.io/images/p2.jpg" />
<img src="http://malsup.github.io/images/p3.jpg" />
<img src="http://malsup.github.io/images/p4.jpg" />
</div>
<div class="content-area">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt dolorem, nemo illo non aspernatur distinctio deleniti repudiandae in reprehenderit, explicabo, ullam. Fuga dolorum voluptates esse animi earum! Sint, officia, molestias!</p>
</div>
</div>
Just use $(".img-area").cycle(0) on mouse leave event.
$('.img-area').cycle({
fx: 'none',
speed: 750,
timeout: 100
}).cycle("pause");
$(".otel-list").hover(function() {
$(".img-area").cycle("resume");
}, function() {
$(".img-area").cycle("pause");
}).mouseleave(function(){
$(".img-area").cycle(0);
});
.otel-list {
width: 700px;
background: #f0f0f0;
border-bottom: 5px solid #ccc;
}
.otel-list:after,
.otel-list-:before {
content: "";
display: table;
clear: both;
}
.img-area {
width: 33%;
float: left;
position: relative;
}
.img-area img {
width: 100%;
position: absolute;
top: 0;
left: 0;
}
.content-area {
float: right;
width: 66%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.cycle2/2.1.6/jquery.cycle2.js"></script>
<div class="otel-list">
<div class="img-area">
<img src="http://malsup.github.io/images/p1.jpg" />
<img src="http://malsup.github.io/images/p2.jpg" />
<img src="http://malsup.github.io/images/p3.jpg" />
<img src="http://malsup.github.io/images/p4.jpg" />
</div>
<div class="content-area">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt dolorem, nemo illo non aspernatur distinctio deleniti repudiandae in reprehenderit, explicabo, ullam. Fuga dolorum voluptates esse animi earum! Sint, officia, molestias!</p>
</div>
</div>