Uncaught DOMException: Not able to run codepen code on my html page - javascript

I tried to implement animation pop up modal from this link .
I carefully copied all the code inside my bootstrap template. Now when i tried to run it, it only shows a button which doesn't work at all. Then i check developer option in chrome i get to see this error
`Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
at createModal (file:///C:/Users/file:///C:/Users/xyz/Desktop /js/popvideo.js:75:8)
at file:///C:/Users/xyz/Desktop/js/popvideo.js:4:13`
and at popvideo.js line number 75 has this code ` body.removeChild(container);
I don't understand when i am getting this error when the pen works fine.
Here is the compete code
<section class="hero-area">
<div id="homelink"> </div>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="block">
<h1 class="wow fadeInUp" data-wow-duration=".5s" data-wow-delay=".3s" >Lorem ipsum dolor sit amet.</h1>
<p class="wow fadeInUp" data-wow-duration=".5s" data-wow-delay=".5s">Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis excepturi ut inventore consectetur quos rerum quibusdam accusamus, labore itaque assumenda consequatur cum saepe velit quidem ipsa facilis. Repellendus, reiciendis quam?</p>
<ul class="list-inline wow fadeInUp" data-wow-duration=".5s" data-wow-delay=".7s">
<li>
<a data-scroll href="#contact" class="btn btn-main">Register</a>
</li>
</ul>
</div>
<div style="margin-top:100px; height:506px; width:332px; float: right; background:url(images/Elaxer-Screen.png)">
<section class="controls">
<button id="open-button">Open</button>
</section>
<section id="modal-1" class="modal-container">
<div class="modal-dialog">
<svg class="modal-svg" viewBox="0 0 100 100" preserveAspectRatio="none">
<polygon class="modal-polygon" />
</svg>
<div class="modal-content">
<h2>I'm a modal</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis excepturi ut inventore consectetur quos rerum quibusdam accusamus, labore itaque assumenda consequatur cum saepe velit quidem ipsa facilis. Repellendus, reiciendis quam?</p>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
</section>
`
JS - popvideo.js
console.clear();
var body = document.body;
var modal = createModal(document.querySelector("#modal-1"));
var openButton = document.querySelector("#open-button");
openButton.addEventListener("click", function() {
modal.open();
});
function createModal(container) {
var content = container.querySelector(".modal-content");
var dialog = container.querySelector(".modal-dialog");
var polygon = container.querySelector(".modal-polygon");
var svg = container.querySelector(".modal-svg");
var point1 = createPoint(45, 45);
var point2 = createPoint(55, 45);
var point3 = createPoint(55, 55);
var point4 = createPoint(45, 55);
var animation = new TimelineMax({
onReverseComplete: onReverseComplete,
onStart: onStart,
paused: true
})
.to(point1, 0.3, {
x: 15,
y: 30,
ease: Power4.easeIn
}, 0)
.to(point4, 0.3, {
x: 5,
y: 80,
ease: Power2.easeIn
}, "-=0.1")
.to(point1, 0.3, {
x: 0,
y: 0,
ease: Power3.easeIn
})
.to(point2, 0.3, {
x: 100,
y: 0,
ease: Power2.easeIn
}, "-=0.2")
.to(point3, 0.3, {
x: 100,
y: 100,
ease: Power2.easeIn
})
.to(point4, 0.3, {
x: 0,
y: 100,
ease: Power2.easeIn
}, "-=0.1")
.to(container, 1, {
autoAlpha: 1
}, 0)
.to(content, 1, {
autoAlpha: 1
})
var modal = {
animation: animation,
container: container,
content: content,
dialog: dialog,
isOpen: false,
open: open,
close: close
};
body.removeChild(container);
function onClick() {
if (modal.isOpen) {
close();
}
}
function onStart() {
body.appendChild(container);
container.addEventListener("click", onClick);
}
function onReverseComplete() {
container.removeEventListener("click", onClick);
body.removeChild(container);
}
function open() {
modal.isOpen = true;
animation.play().timeScale(2);
}
function close() {
modal.isOpen = false;
animation.reverse().timeScale(2.5);
}
function createPoint(x, y) {
var point = polygon.points.appendItem(svg.createSVGPoint());
point.x = x || 0;
point.y = y || 0;
return point;
}
return modal;
}
CSS
/*Pop Up Video*/
.buttonpop {
cursor: pointer;
padding: 0 6px;
min-width: 88px;
min-height: 36px;
}
.controls {
padding: 24px;
}
.modal-container {
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0;
left: 0;
z-index: 1;
width: 100%;
height: 100vh;
overflow: hidden;
background: rgba(0, 0, 0, 0.15);
opacity: 0;
visibility: hidden;
}
.modal-dialog {
width: 70vmin;
height: 70vmin;
position: relative;
overflow: hidden;
}
.modal-svg {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.modal-polygon {
fill: #ab47bc;
}
.modal-content {
position: relative;
top: 0;
left: 0;
padding: 24px;
visibility: hidden;
opacity: 0;
color: rgba(255, 255, 255, 0.87);
}
Please guide me to resolve this issue. P.S- I am not good in JS

The problem is that your #modal-1 element isn't the child of the body container as it is the case with the codepen you got the code from. It's a child of the unnamed div with the background:url(images/Elaxer-Screen.png),which is why it gives you the error. What you can simply do is add a parent container and reference it in your js file.
Here is how I did it:
Step 1: Edit your HTML file by adding parentContainer id.
<div id="parentContainer" style="margin-top:100px; height:506px; width:332px; float: right; background:url(images/Elaxer-Screen.png)">
<section class="controls">
<button id="open-button">Open</button>
</section>
<section id="modal-1" class="modal-container">
<div class="modal-dialog">
<svg class="modal-svg" viewBox="0 0 100 100" preserveAspectRatio="none">
<polygon class="modal-polygon" />
</svg>
<div class="modal-content">
<h2>I'm a modal</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis excepturi ut inventore consectetur quos rerum quibusdam accusamus, labore itaque assumenda consequatur cum saepe velit quidem ipsa facilis. Repellendus, reiciendis quam?</p>
</div>
</div>
</section>
</div>
Step 2: Initialize parent container as a variable.
var parentCont = document.querySelector("#parentContainer");
Step 3: Remove the body variable on line 76 and use the parent container variable.
parentCont.removeChild(container);
Here is a reference to my codepen: my codepen
Works fine. Good luck and hope this helps!

Related

jQuery Find Closest Element Inside div Based on mousemove Event

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!

Expanding Image Grid Issues

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!

How to set collapse on all other divs when one div is open?

I have seen many questions but none are similar to my case. I have bootstrap collapse and show for a few div contents. The div content shows when title is clicked. I want to close all other div contents when I click another content's title.
The color of the title div is gray and should change to white when its content shows. Once the content is collapsed, title div color should back to gray.
Here's my code:
function collapse (e, id, collapasibleName) {
var toggleColor = document.getElementById(id);
var collapsibles = document.getElementById(collapasibleName);
if(collapsibles.className == 'home__questions-content collapse' || collapsibles.className == 'home__questions-content collapsed')
{
alert("Sdfsdfdsf")
toggleColor.classList.remove('home__questions-title-show');
}
if(collapsibles.className == 'home__questions-content collapse show') {
alert("in show")
toggleColor.classList.add('home__questions-title-show');
}
}
.home__more-questions-content {
padding-right: 40px;
padding-left:40px;
padding-bottom: 20px;
background-color: $white-color;
position:relative;
max-width: 1080px;
margin: auto;
}
.home__questions-content-tile {
margin-bottom: 10px;
border:1px solid #eee;
}
.home__questions-content-title {
padding:20px;
background-color: #000
cursor: pointer;
}
.home__questions-content {
padding-top: 0;
padding-right:20px;
padding-left:20px;
padding-bottom:20px;
}
.home__questions-title-show { background-color: #fff; }
.collapse {
display:none;
}
.collapse.show {
display: block;
}
.collapsing {
position: relative;
height: 0;
overflow: hidden;
transition: height 0.35s ease;
}
<div class="home__more-questions-content" id="accordion">
<div class="home__questions-content-tile">
<div class="home__questions-content-title" data-toggle="collapse" data-target="#collapsible-one" data-parent="#accordion" id="collapse-one" onclick="collapse(event, this.id,'collapsible-one');">
<h2>
// title 1 here
</h2>
</div>
<div class="home__questions-content collapse" id="collapsible-one">
//title 1's content here
</div>
</div>
<div class="home__questions-content-tile">
<div class="home__questions-content-title" data-toggle="collapse" data-target="#collapsible-two" data-parent="#accordion" id="collapse-two" onclick="collapse(event, this.id,'collapsible-two');">
<h2>
//title 2
</h2>
</div>
<div class="home__questions-content collapse" id="collapsible-two">
//title 2's content here
</div>
</div>
<div class="home__questions-content-tile">
<div class="home__questions-content-title" data-toggle="collapse" data-target="#collapsible-three" data-parent="#accordion" id="collapse-three" onclick="collapse(event, this.id, 'collapsible-three');">
<h2>
//title 3
</h2>
</div>
<div class="home__questions-content collapse" id="collapsible-three">
// title 3's content here
</div>
</div>
</div>
Here is the code, explanation is in the comment of the question.
Add new code
if (e.target.parentNode.classList.contains('active')) {
e.target.parentNode.classList.remove('active')
return
}
If current block is opened, then close it and return from further processing.
const container = document.querySelector('.container')
container.addEventListener('click', e => {
if (e.target.parentNode.classList.contains('active')) {
e.target.parentNode.classList.remove('active')
return
}
const collapsable = document.querySelectorAll('.item')
Array.prototype.forEach.call(collapsable, el => {
el.classList.remove('active')
})
e.target.parentNode.classList.add('active')
})
.container {
width: 500px;
margin: 0 auto;
color:darkslategrey;
}
.item {
margin: 10px 0;
border-bottom: 1px solid #666;
padding: 5px 10px;
}
.item.active h3 {
color:aquamarine;
}
p {
overflow: hidden;
transition: height .5s ease;
height: 0px;
}
.item.active p {
height: 80px;
}
<div class="container">
<div class="item active">
<h3>I am a title</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Magni minus neque nisi, rem doloribus unde quisquam, similique distinctio voluptate mollitia praesentium quo ut magnam ducimus nemo vitae soluta impedit harum?</p>
</div>
<div class="item">
<h3>I am a title</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Magni minus neque nisi, rem doloribus unde quisquam, similique distinctio voluptate mollitia praesentium quo ut magnam ducimus nemo vitae soluta impedit harum?</p>
</div>
<div class="item">
<h3>I am a title</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Magni minus neque nisi, rem doloribus unde quisquam, similique distinctio voluptate mollitia praesentium quo ut magnam ducimus nemo vitae soluta impedit harum?</p>
</div>
</div>

Render only selected element, React JS

I am trying to toggle class in one of my react component.
The idea is to add class when the mouse enter and to remove the class when the mouse leave only in the element only the element in where the user perform the actions. However this is not the case as when the action is being performed all the element with the function are behaving equally.
This is my code so far:
export default class Projects extends Component{
constructor(){
super();
this.state = {
isHovered : false
}
}
//handle mouse enter
handleMouseEnter = () =>{
this.setState({
isHovered : true
});
}
//handle mouse leave
handleMouseLeave = () =>{
this.setState({
isHovered : false
});
}
//render component
render(){
let display = "";
if(this.state.isHovered === true){
display = "active";
}else{
display = "disable";
}
return(
<section className="projects">
{/*section project wrapper*/}
<div className="p-wrapper">
<h1 className="title">Projects</h1>
<hr/>
{/*projet wrapper*/}
<div className="projects-wrapper">
{/*project item wrapper*/}
<div className="project-item" onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>{/*FMA Web development*/}
<div className={"p-description " + display}>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure quos dolorem, ipsa eaque minima saepe fugit hic libero recusandae! Obcaecati esse odit id incidunt vitae aperiam dicta atque blanditiis sint?</p>
</div>
<div className="p-image">
<img src="asset/img/fma_web.png" alt="FMA Web Development"/>
</div>
</div>
<div className="project-item" onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>{/*Web development using php*/}
<div className={"p-description " + display}>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure quos dolorem, ipsa eaque minima saepe fugit hic libero recusandae! Obcaecati esse odit id incidunt vitae aperiam dicta atque blanditiis sint?</p>
</div>
<div className="p-image">
<img src="asset/img/web_dev_php.png" alt="FMA Web Development Using PHP"/>
</div>
</div>
<div className="project-item" onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>{/*Movie Catalog*/}
<div className={"p-description " + display}>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure quos dolorem, ipsa eaque minima saepe fugit hic libero recusandae! Obcaecati esse odit id incidunt vitae aperiam dicta atque blanditiis sint?</p>
</div>
<div className="p-image">
<img src="asset/img/movie_catalog.png" alt="Movie Catalog"/>
</div>
</div>
</div>
</div>
</section>
);
}
}
I have read the use of key in the documentation and read other question especially this one LINK,however when I try to implement I do not get the desired result.
===========================
EDIT
This is what I get now.
As you can see when I hover both of the element triggers.
This is my CSS Code:
/*Projects Start*/
.projects{
width: 100%;
}
.p-wrapper{
margin: 0 auto;
width: 90%;
height: 100%;
}
.projects-wrapper{
margin-top: 2rem;
width: 100%;
display: flex;
justify-content: center;
flex-wrap: wrap;
}
.project-item{
margin: 1rem;
width: 30%;
position: relative;
box-shadow: 2px 3px 37px -5px rgba(0,0,0,0.84);
}
.p-description{
position: absolute;
height: 100%;
width: 100%;
background-color: rgba(43, 40, 40, 0.61);
color: white;
}
.p-description p {
margin: 1rem;
}
.p-title{
margin: 1rem;
}
.active{
display: block;
transition: all 2s ease-in;
}
.disable {
display: none;
}

how to return first image with cycle plugin

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>

Categories

Resources