jQuery Find Closest Element Inside div Based on mousemove Event - javascript

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!

Related

Scrolling to the bottom of a span automatically with javascript

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>

Show more/less if text does not fit

I am creating some cards with dynamic data using jquery. There is a description property that either fits on the card or not. When it does not fit, i would like to keep the card the same size as the others but add a "show more/less" button that would expand the card to show the rest of the description.
I have created a fiddle showing the card creation as well as what i have tried so far.
At this point i have a function checkTruncation that will check if the text would fit in its container or not. The issue seems to rely on the fact that the elements are not yet rendered so their width is 0 which makes the function return always true.
The function is as this:
let checkTruncation = function (jqueryElement) {
var $element = jqueryElement;
if ($element) {
var $c = $element
.clone()
.css({ display: 'inline', width: 'auto', visibility: 'hidden' })
.appendTo('body');
let truncated = $c.width() > $element.width()
console.log($c.width(), $element.width(), $c.width() > $element.width())
$c.remove();
return truncated;
}
return false;
}
Also, instead of me reinventing the wheel, is there any suggested library that could achieve this functionality? I know i have seen such behavior, but cannot remember where.
UPDATE
In the fiddle above, i am just calling the getCard function, which is responsible to provide the template for the card, twice just to show some sample. In the real life situation i am getting data through ajax and populating the cards using the following when a user clicks on a button:
$('.fetchButton').on('click', function(){
$.get(url, filter)
.done(function (data) {
jQuery.each(data, function (index, item) {
$('.container').append(getCard(item));
})
}
})
UPDATE 2
With the help of #LGSon i have come to this scenario which is mostly using CSS to achieve what i need. Still the answer given is valid and did solve my issue so i will keep it as an answer.
In addition to given answer, which explained why the original code didn't work, here is a different approach, showing how one can use CSS to show/hide a "Read more..." button
With absolute: position and overflow: hidden we can hide a "button" at the bottom of a "text" element, and when that element reach the "wrapper's" height, the hidden "button" becomes visible.
I also made use of a pseudo element and data-* attribute to keep "button text" in the markup, and the CSS attr() to toggle it when showing/hiding the text.
Stack snippet
document.querySelectorAll('.readmore').forEach( function(link) {
link.addEventListener('click', function() {
this.closest('.wrapper').classList.toggle('show');
});
});
.wrapper {
height: 70px;
border: 1px solid gray;
overflow: hidden;
}
.wrapper.show {
height: auto;
}
.text {
position: relative;
overflow: hidden;
}
.readmore {
position: absolute;
width: 100%;
top: 52px;
left: 0;
background: white;
color: red;
cursor: pointer;
}
.readmore::before {
content: attr(data-more)
}
.wrapper.show .readmore {
position: relative;
top: auto;
display: block;
}
.wrapper.show .readmore::before {
content: attr(data-less)
}
<div class="wrapper">
<div class="text">
Some smaller dummy text here
<span class="readmore" data-more="Show more..." data-less="Show less..."></span>
</div>
</div>
<div class="wrapper">
<div class="text">
Some bigger dummy text here <br>
Some bigger dummy text here <br>
Some bigger dummy text here <br>
Some bigger dummy text here <br>
Some bigger dummy text here <br>
<span class="readmore" data-more="Show more..." data-less="Show less..."></span>
</div>
</div>
If possible, the "Show more/less..." text can of course be set in the CSS, to simplify maintenance and have it in one place.
document.querySelectorAll('.readmore').forEach( function(link) {
link.addEventListener('click', function() {
this.closest('.wrapper').classList.toggle('show');
});
});
.wrapper {
height: 70px;
border: 1px solid gray;
overflow: hidden;
}
.wrapper.show {
height: auto;
}
.text {
position: relative;
overflow: hidden;
}
.readmore {
position: absolute;
width: 100%;
top: 52px;
left: 0;
background: white;
color: red;
cursor: pointer;
}
.readmore::before {
content: 'Show more...'
}
.wrapper.show .readmore {
position: relative;
top: auto;
display: block;
}
.wrapper.show .readmore::before {
content: 'Show less...'
}
<div class="wrapper">
<div class="text">
Some smaller dummy text here
<span class="readmore"></span>
</div>
</div>
<div class="wrapper">
<div class="text">
Some bigger dummy text here <br>
Some bigger dummy text here <br>
Some bigger dummy text here <br>
Some bigger dummy text here <br>
Some bigger dummy text here <br>
<span class="readmore"></span>
</div>
</div>
Updated based on a comment
Here is an updated Stack snippet version of your Fiddle/Codepen sample's
let getCard = function(options) {
let item = options.data;
let $parent = options.parent;
let outerDiv = $('<div>').addClass('shops-content-right');
let boxDiv = $('<div>').addClass('boxes-right row');
let shopDiv = $('<div>').addClass('one-shop-box col-md-6 offset-md-3');
let cubeDiv = $('<div>').addClass('cube text-center');
let wrapperDiv = $('<div>').addClass('wrapper');
let textDiv = $('<div>').addClass('text');
let descriptionP = $('<p>').addClass('text-disc').text(item.description);
let loadMoreP = $('<span>More >').addClass('readmore');
textDiv.append([descriptionP, loadMoreP]);
wrapperDiv.append(textDiv);
cubeDiv
.append(wrapperDiv);
shopDiv.append(cubeDiv);
boxDiv.append(shopDiv);
outerDiv.append(boxDiv);
$parent.append(outerDiv);
loadMoreP.on('click', function() {
if (wrapperDiv.hasClass('collapsed')) {
wrapperDiv.removeClass('collapsed');
loadMoreP.text("More >");
} else {
wrapperDiv.addClass('collapsed');
loadMoreP.text("Less <");
}
})
return outerDiv;
}
$('.fetchButton').on('click', function() {
getCard({
data: {
description: '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'
},
parent: $('.container'),
lines: 3
})
getCard({
data: {
description: 'Lorem ipsum dolor sit amet, consectetur'
},
parent: $('.container'),
lines: 3
})
})
.row {
background: #f8f9fa;
margin-top: 20px;
}
.col {
border: solid 1px #6c757d;
padding: 10px;
}
.one-shop-box {
border: 1px solid;
}
.shops-content-right .one-shop-box .cube p.text-disc {
font-size: 16px;
/*height: 50px;*/
overflow: hidden;
}
.wrapper {
height: 90px;
overflow: hidden;
}
.wrapper.collapsed {
height: auto;
}
.text {
position: relative;
overflow: hidden;
}
.readmore {
position: absolute;
width: 100%;
top: 72px;
left: 0;
background: white;
color: red;
}
.wrapper.collapsed .readmore {
position: relative;
top: auto;
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--
Bootstrap docs: https://getbootstrap.com/docs
-->
<div class="container">
<button class="fetchButton">
Fetch Data
</button>
</div>
This happens beacuse you doesn't append your element to document, so its width is 0. So, update your code as the following:
let checkTruncation = function($element) {
if ($element) {
var $c = $element
.clone()
.css({ display: 'inline', width: 'auto', visibility: 'hidden' })
.appendTo('body');
let truncated = $c.width() > $element.width();
// console.log($c.width(), $element.width(), $c.width() > $element.width());
$c.remove();
return truncated;
}
return false;
};
let baseUrl ='';
let getCard = function(item, $parent) {
let outerDiv = $('<div>').addClass('shops-content-right');
let boxDiv = $('<div>').addClass('boxes-right row');
let shopDiv = $('<div>').addClass('one-shop-box col-md-6 offset-md-3');
let cubeDiv = $('<div>').addClass('cube text-center');
let descriptionP = $('<p>').addClass('text-disc').text(item.description).addClass('collapsed');
let loadMoreP = $('<p>').css({ 'font-size': '16px', 'cursor': 'pointer' }).text("More >");
cubeDiv.append(descriptionP).append(loadMoreP);
shopDiv.append(cubeDiv);
boxDiv.append(shopDiv);
outerDiv.append(boxDiv);
$parent.append(outerDiv);
loadMoreP.on('click', function () {
if (descriptionP.hasClass('collapsed')) {
descriptionP.removeClass('collapsed');
loadMoreP.text("Less <");
} else {
descriptionP.addClass('collapsed');
loadMoreP.text("More >");
}
});
if (checkTruncation(descriptionP)) {
loadMoreP.show();
} else {
loadMoreP.hide();
}
};
const $container = $('.container');
getCard({
description: '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'
}, $container);
getCard({
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
}, $container);
.row {
background: #f8f9fa;
margin-top: 20px;
}
.col {
border: solid 1px #6c757d;
padding: 10px;
}
.one-shop-box {
border:1px solid;
}
.shops-content-right .one-shop-box .cube p.text-disc {
font-size: 16px;
height: 50px;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container"></div>
I pass to the function getCard() the container element, and it append the new element to it before it calls to the function checkTruncation().
And update your code that calls getCard() as follows:
const $container = $('.container');
$('.fetchButton').on('click', function() {
$.get(url, filter).done(function(data) {
$.each(data, function(index, item) {
getCard(item, $container);
});
});
});

How to scroll the circle using mouse wheel?

I have one circle and I have to rotate 360 deg using mouse scroll wheel or arrow but it will start when circle touches the blue border. Now my code is working when I scroll it and touch the blue border. But I have to scroll the circle using the mouse wheel. I mean using mouse wheel I have to rotate the circle also reverse.
Is there any idea how to do that?
$(window).bind('scroll', function() {
var l_360 = document.getElementById("l_360");
var controller = new ScrollMagic.Controller();
var tween = TweenLite.to(l_360, 3, {
x: -1910,
y: 350,
rotation: 360,
opacity: '1',
ease: Linear.easeOut
});
var scene = new ScrollMagic.Scene({
triggerElement: "#l_360"
})
.setTween(tween)
.setClassToggle('#l_360', 'fade-in')
.addTo(controller);
});
.parent_img {
position: fixed;
right: 0;
top: 0;
width: 100%;
text-align: right;
}
.content,
.content_2,
.content_3 {
width: 700px;
position: relative;
}
.content {
margin-top: 400px;
}
.main_l {
position: fixed;
right: 115px;
top: 20px;
z-index: 100;
}
.main_l .l_circle {
width: 250px;
height: 250px;
background-color: #EFBD40;
border-radius: 50%;
display: flex;
}
.main_l .l_circle h2 {
margin: auto;
color: #fff;
font-size: 35px;
}
.blue {
background-color: #0082ff;
transform: skew(0deg, -10deg);
z-index: -1;
/*color: #fff;*/
}
.blue .container {
transform: skew(0deg, 10deg);
position: relative;
top: 50px;
}
<div class="main_l" id="l_360">
<div class="l_circle">
<h2>360 circle</h2>
</div>
</div>
<div class="blue">
<div class="container">
<div class="content">
<h2>This is just for testing</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing 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>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenMax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/plugins/ScrollToPlugin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.2/plugins/CSSPlugin.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/ScrollMagic.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/plugins/animation.gsap.js"></script>
Using the wheel event will give you deltas for the direction you scroll the wheel. For example, to detect a vertical wheel movement the property deltaY will be either a negative value (forward) or positive (backward):
You can use the value directly if you wish, but it may vary depending on browser and system.
Example
var div = document.querySelector("div");
var angle = 0;
document.onwheel = function(e) {
if (e.deltaY) { // we have a wheel for vertical (common) direction
e.preventDefault();
angle += e.deltaY < 0 ? 4 : -4; // what direction?
div.style.transform = "rotate(" + angle + "deg)"; // do something
}
};
body {margin:30px}
div {border-radius:50%;border:3px solid #09f;width:150px;height:150px;}
<div> O</div>

JQuery lightbox work with multiple galleries/links

I am trying to make this code I made into a library:
$.fn.boxify = function() {
var imageSliding = $('.box > .img');
$(this).click(function() {
$('.backdrop, .box').animate({
'opacity': '.50'
}, 300, 'linear');
$('.box').animate({
'opacity': '1.00'
}, 300, 'linear');
$('.backdrop, .box').css('display', 'block');
});
$('.close').click(function() {
close_box();
});
$('.backdrop').click(function() {
close_box();
});
function close_box() {
$('.backdrop, .box').animate({
'opacity': '0'
}, 300, 'linear', function() {
$('.backdrop, .box').css('display', 'none');
});
}
/* Slider */
var speed = 100;
$(".prev").click(function() {
var gallery = $(this).closest('.box').find("ul.gallery"),
now = gallery.children(":visible"),
last = gallery.children(":last"),
prev = now.prev();
prev = prev.index() == -1 ? last : prev;
now.fadeOut(speed, function() {
prev.fadeIn(speed);
});
});
$(".next").click(function() {
var gallery = $(this).closest('.box').find("ul.gallery"),
now = gallery.children(":visible"),
first = gallery.children(":first"),
next = now.next();
next = next.index() == -1 ? first : next;
now.fadeOut(speed, function() {
next.fadeIn(speed);
});
});
$(".gallery li").click(function() {
var first = $(this).parent().children(':first'),
next = $(this).next();
next = next.index() == -1 ? first : next;
$(this).fadeOut(speed, function() {
next.fadeIn(speed);
});
});
};
$( "a" ).boxify(); // Makes all the links green.
body {
font-family: Helvetica, Arial;
}
.backdrop {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background: #000;
opacity: .0;
filter: alpha(opacity=0);
z-index: 50;
display: none;
}
.box {
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
left: 50%;
background: black;
text-align: left;
z-index: 51;
padding: 0;
margin: 0;
display: none;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow: 0px 0px 5px #444444;
-webkit-box-shadow: 0px 0px 5px #444444;
box-shadow: 0px 0px 5px #444444;
border: 10px solid #000;
color: white;
width: 40%;
}
#media (min-width: 320px) and (max-width: 900px) {
.box {
width: 98%;
}
}
#media (min-width: 901px) and (max-width: 1200px) {
.box {
width: 60%;
}
}
#media (min-width: 1201px) {
.box {
width: 48%;
}
}
.box img {
width: 100%;
}
.caption {
padding-top: 10px;
font-size: 15px;
}
.prev,
.next {
position: relative;
padding: 3px;
cursor: pointer;
float: right;
border: 1px solid black;
}
.prev:active,
.next:active {
background-color: white;
color: black;
}
.gallery li {
display: none;
list-style: none;
margin-left: -40px;
}
.gallery li:first-child {
display: block;
}
.gallery img {
max-height: 550px;
}
.slideButtons {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
<h1>Welcome Within</h1>
Open Lightbox
<div class="backdrop"></div>
<div class="box">
<ul class="gallery" id="olympGallery">
<li><img src="http://urbanphenomena.net/imgs/trabzoni/trabzoni1.png" alt="" title="" /></li>
<li><img src="http://urbanphenomena.net/imgs/trabzoni/trabzoni2.png" alt="" title="" /></li>
<li><img src="http://urbanphenomena.net/imgs/trabzoni/trabzoni3.png" alt="" /></li>
</ul>
<div class="slideButtons">
<span class="next">Next</span>
<span class="prev">Previous</span>
</div>
<div class="caption">
<p>This thing is called 'Caption'. Let me tell you:</p>
<hr />
<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>
</div>
</div>
You see that .box class? As a user I wanna infinitely add more box containing different images and captions!
When I added another <a> which is the Lightbox link to the box, the both boxes display on the same time. I know that the same code is reused this way, but that's what I'm trying to do:
Somehow keep the same code without adding more and more code. Yet, when I add more boxes they are completely different from the others (different images)
You can modify your .click function to use this one:
$(this).click(function(event) {
var lightBoxes = $('a.lightbox'); //Retrieves all a.lightboxes of the page
for (var i = 0; i < lightBoxes.length; i++) {
if (lightBoxes[i] == event.target) { //Checks the clicked element position in the array
//Displays the common .backdrop div
$('.backdrop').animate({
'opacity': '.50'
}, 300, 'linear').css('display', 'block');
//Displays the 'i' .box div
$('.box').eq(i).animate({
'opacity': '1.00'
}, 300, 'linear').css('display', 'block');
break;
}
}
});
This code will check all the 'a' elements with the .lightbox class and will check which one was clicked. Knowing the index (i) of the 'a' element clicked, then the 'i' .box element will display.
Note that the .backdrop element should be unique in the HTML and don't need to be repeated. In the HTML you just need to add a new a href element and a new div .box for each a.
Open Lightbox 2
<div class="box">
<ul class="gallery" id="olympGallery">
<li><img src="http://urbanphenomena.net/imgs/trabzoni/trabzoni1.png" alt="" title="" /></li>
<li><img src="http://urbanphenomena.net/imgs/trabzoni/trabzoni2.png" alt="" title="" /></li>
<li><img src="http://urbanphenomena.net/imgs/trabzoni/trabzoni3.png" alt="" /></li>
</ul>
<div class="slideButtons">
<span class="next">Next</span>
<span class="prev">Previous</span>
</div>
<div class="caption">
<p>This thing is called 'Caption'. Let me tell you:</p>
<hr />
<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>
</div>
</div>
Hope this is what you need!

How to Create a Link to a DIV

Here is what im working on... A maximizable and minimizable pop-up that is called by an hyperlink.
<html>
<style type="text/css">
.pop_out {
background: #333;
border-radius: 5px 5px 0 0;
box-shadow: 0px 0px 10px #000;
}
.minimized {
display: inline-block;
margin-right: 10px;
bottom: 0;
width: 250px;
height: 60px;
overflow: hidden;
}
.maximized {
top: 0;
position: fixed;
display: block;
width: auto;
height: auto;
/* Whatever styling you want when maximized, as long as you add the same styling to minimized class to change it back */
}
.close_pop {
cursor: pointer;
color: #fff;
}
.close_pop:hover {
color: red;
}
.expand_collapse {
margin-right: 10px;
cursor: pointer;
color: #fff;
height: 3px;
}
.expand_collapse:hover {
color: #ccc;
}
a {
position: fixed;
top: 150;
}
</style>
<script type="text/javascript">
var max = true;
function expand_collapse(elem) {
var top_div = elem.parentNode.parentNode.parentNode;
if (max === false) {
elem.innerHTML = "▼";
top_div.classList.toggle("minimized", false);
top_div.classList.toggle("maximized", true);
max = true;
} else if (top_div.classList.contains("maximized")) {
elem.innerHTML = "▲";
top_div.classList.toggle("minimized", true);
top_div.classList.toggle("maximized", false);
max = false
}
}
function close_pop(elem) {
var top_div = elem.parentNode.parentNode.parentNode;
top_div.style.display = 'none';
if (top_div.classList.contains("maximized")) {
max = false;
}
}
</script>
CLICK HERE<!--Right Here -->
<div style="position:fixed;bottom:0px;">
<div class="pop_out maximized">
<div style="padding:2px;position:relative;"> <span style="margin-left:10px;">Tab 1</span>
<span style="position:absolute;right:15px;">
<span class="expand_collapse" onclick="expand_collapse(this);">▼</span>
<span class="close_pop" onclick="close_pop(this);">&times</span></span>
</div>
<div style="background:white;font-size:15px;padding:2px;">The standard Lorem Ipsum passage, used since the 1500s "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.</div>
</div>
</div>
But the pop up opens with the page and i want the pop up to only be opened when the hyperlink commented is clicked and not when the page is loaded. Any help will be much appreciated. I have tried different methods on the hyperlink but to no avail.
Please check the link below
$(document).ready(function() {
$('.show-popup').on('click', function() {
$('.popup').fadeIn();
});
$('.close_pop').on('click', function() {
$('.popup').fadeOut();
});
});
.popup {
display: none;
}
.pop_out {
background: #333;
border-radius: 5px 5px 0 0;
box-shadow: 0px 0px 10px #000;
}
.minimized {
display: inline-block;
margin-right: 10px;
bottom: 0;
width: 250px;
height: 60px;
overflow: hidden;
}
.maximized {
top: 0;
position: fixed;
display: block;
width: auto;
height: auto;
/* Whatever styling you want when maximized, as long as you add the same styling to minimized class to change it back */
}
.close_pop {
cursor: pointer;
color: #fff;
}
.close_pop:hover {
color: red;
}
.expand_collapse {
margin-right: 10px;
cursor: pointer;
color: #fff;
height: 3px;
}
.expand_collapse:hover {
color: #ccc;
}
a {
position: fixed;
top: 150;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<a class="show-popup" href="#">CLICK HERE</a>
<!--Right Here -->
<div class="popup" style="position:fixed;bottom:0px;">
<div class="pop_out maximized">
<div style="padding:2px;position:relative;"> <span style="margin-left:10px;">Tab 1</span>
<span style="position:absolute;right:15px;">
<span class="expand_collapse" onclick="expand_collapse(this);">▼</span>
<span class="close_pop">&times</span></span>
</div>
<div style="background:white;font-size:15px;padding:2px;">The standard Lorem Ipsum passage, used since the 1500s "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.
</div>
</div>
</div>
The pop-up element isn't being hidden on initial page load.
Add style to the pop-up element in CSS.
display:none
Give the pop-up element an ID attribute for easier Javascript targeting
id="pop1"
Add attribute to the hyperlink
onclick="open_pop('#pop1')"
Add javascript function
function open_pop(elem)
{
elem.style.display = 'block';
}
Or to synchronise more effectively with your code, give the pop-up one of your custom classes to modify the display style.
I would also consider using ID's for Javascript selection as opposed to crawling through parents which could break the code if children elements or added or removed from the tree.
in simple code,
html
<div id="welcomeDiv" style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv()" />
javascript
function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
}
I could not share my jsfiddle link. so this helps you i guess.
OR
Just make the div style = "display:none" on mouse click toggle the display.

Categories

Resources