Click a button that is visible in viewport - javascript

I have several buttons in div in an html page , I want to click the buy button which is visible in viewport , when I press the key B.
$(document).keydown(function(e) {
if (e.keyCode == 66) {
//click the visible buy button in viewport ,
$(".buy").click();
}
});
<section>
<div class="buy">BUY</div>
<div class="buy">SELL</div>
</section>
<section>
<div class="buy ">BUY</div>
<div class="buy ">SELL</div>
</section>
<section>
<div class="buy ">BUY</div>
<div class="buy ">SELL</div>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note : there are 100's of buy button , but only 1 buy button appears at a time in viewport

If other .buy buttons are invisible really, you can try this:
$(".buy:visible").click();
Else, get your visible section by this:
var myVisibleSection = document.elementFromPoint(x+10, y+10);
(The x and y are position of parent of your sections that is matches with visible section and you can get them by jquery (.offset()) or vanilla js. 10's are sum of border and padding of the parent.)
Now:
myVisibleSection.find(".buy").click();

You could try to use this convenient function which tells us if the button is visible in the viewport, which I found in this blog. Also please make the css class sell which is the same as buy and set it for the sell div's, since we need to distinguish between the two buttons!
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(document).keydown(function(e) {
if (e.keyCode == 66) {
//click the visible buy button in viewport ,
$(".buy").each(function( index ) {
if($(this).isInViewport()){
console.log($(this).html() + " - " + index);
$(this).click();
}
});
}
});
section {
height: 100vh;
width: 100%;
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<div class="buy">BUY</div>
<div class="sell">SELL</div>
</section>
<section>
<div class="buy">BUY</div>
<div class="sell">SELL</div>
</section>
<section>
<div class="buy">BUY</div>
<div class="sell">SELL</div>
</section>

Related

How to reuse a piece of Javascript multiple times in one page

I'm new to building websites and have a (probably quite basic) question about using a Javascript function that's been written for a slideshow. I have a one-page website which uses multiple slideshow units – made up of the slideshow div, holder and a counter (e.g. 1/4), all of which is controlled by the following js:
var currentSlide = 0
var totalSlides = $('.holder div').length
var nextSlide = function() {
console.log('nextSlide')
currentSlide = currentSlide + 1
if (currentSlide >= totalSlides) {
currentSlide = 0
}
var leftPosition = (-currentSlide * 100) + 'vw'
$('.holder').css('left', leftPosition)
var slideNumber = currentSlide + 1
$('.steps').text(slideNumber + '/' + totalSlides)
}
var prevSlide = function() {
currentSlide = currentSlide - 1
if (currentSlide < 0) {
currentSlide = totalSlides - 1
}
var leftPosition = (-currentSlide * 100) + 'vw'
$('.holder').css('left', leftPosition)
var slideNumber = currentSlide + 1
$('.steps').text(slideNumber + '/' + totalSlides)
}
var autoSlide = setInterval(function() {
nextSlide()
}, 100000000)
$('.next').on('click', function() {
clearInterval(autoSlide)
nextSlide()
})
$('.prev').on('click', function() {
clearInterval(autoSlide)
prevSlide()
})
var slideNumber = currentSlide + 1
$('.steps').text(slideNumber + '/' + totalSlides)
$('body').on('keydown', function(event) {
var keyCode = event.keyCode
if (keyCode == 37) {
clearInterval(autoSlide)
prevSlide()
}
if (keyCode == 39) {
clearInterval(autoSlide)
nextSlide()
}
})
My set up in HTML is this:
<main class="scroll-container">
<section id="project-1" class="toxic-yellow">
<div class="slideshow">
<div class="holder">
<div class="slide-1 image next"><img src="images/01.jpg"></div>
<div class="slide-2 image next">
<p class="project-text">
Project 1, 3D, 2020<br>
Insert the project text here insert the project text here insert the project text here insert the project text here insert the project text here
</p>
</div>
<div class="slide-3 image next"><img src="images/05.jpg"></div>
<div class="slide-4 image next"><img src="images/02.jpg"></div>
<div class="slide-5 image next"><img src="images/04.jpg"></div>
<div class="slide-6 image next"><img src="images/06.jpg"></div>
</div>
</div>
<p class="caption">Project 1</p>
<p class="steps"></p>
</section>
<section id="project-2" class="lilac">
<div class="slideshow">
<div class="holder">
<div class="slide-1 image next"><img src="images/05.jpg"></div>
<div class="slide-2 image next">
<p class="project-text">
Project 1, 3D, 2020<br>
Insert the project text here insert the project text here insert the project text here insert the project text here insert the project text here
</p>
</div>
<div class="slide-3 image next"><img src="images/05.jpg"></div>
<div class="slide-4 image next"><img src="images/02.jpg"></div>
<div class="slide-5 image next"><img src="images/04.jpg"></div>
<div class="slide-6 image next"><img src="images/06.jpg"></div>
</div>
</div>
<p class="caption">Project 2</p>
<p class="steps"></p>
</section>
And so on. I have 12 slideshows in total on the same page. The problem I'm encountering is that the script applies globally across the whole page but I'd like to control each slideshow independently of each other. Is there a way to reuse this script and apply it separately to each instance of the slideshow?
Thanks for your help!
You can use JavaScript Functions or Classes.
W3Schools Reference Functions
W3Schools Reference Classes
$('body').on('keydown', function(event)
With this you are applying change to all of the elements.
Judging by your code, you can trigger the event listener to change the slides only to the child elements of the parent element(section) which has id of "project-X". Have a look here

jQuery Scrolling to Next Section Not Working Properly

I am trying to develop a site where if user press n or N key on the keyboard, the page will auto scroll to the next section. Same applies to the previous section. But I am facing a problem, to scroll next section, sometimes I have to press n twice. On the contrary, it's skipping two sections instead of one while I am pressing p key to go back the previous section. How can I solve this?
I am including my code here:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function ScrollTo(address) {
$('html, body').animate({
scrollTop : ($('#' + address).offset().top)
}, 700);
}
</script>
</head>
<body>
<section id="section1">
<h1>section1</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>
<section id="section2">
<h1>section2</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>
<section id="section3">
<h1>section3</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>
<section id="section4">
<h1>section4</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>
<section id="section5">
<h1>section5</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>
<section id="section6">
<h1>section6</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>
<section id="section7">
<h1>section7</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>
<section id="section8">
<h1>section8</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>
<section id="section9">
<h1>section9</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>
<section id="section10">
<h1>section10</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>
<script type="text/javascript">
var sections = [];
$(document).find("section").each(function() {
sections.push(this.id);
});
var sectionIndex = 0;
$(document).keyup(
function(evt) {
var elid = $(document.activeElement).is("input, textarea");
if (elid) {
return;
}
if ((evt.keyCode == 80 | evt.keyCode == 112)
& sectionIndex > 0) {
sectionIndex=sectionIndex-1;
ScrollTo(sections[sectionIndex]);
} else if ((evt.keyCode == 78 | evt.keyCode == 110)
& sectionIndex < sections.length - 1) {
sectionIndex=sectionIndex+1;
ScrollTo(sections[sectionIndex]);
}
});
$(document).scroll(
function() {
$('section').each(
function() {
if ($(this).position().top <= $(document).scrollTop() && ($(this).position().top + $(this).outerHeight()) > $(document).scrollTop()) {
sectionIndex = sections.indexOf(($(this).attr('id')));
}
});
});
</script>
</body>
</html>
Hint: Change your code a little bit...
$('section').each(
function () {
this.style.background = '';
if ($(this).position().top <= $(document).scrollTop() && ($(this).position().top + $(this).outerHeight()) > $(document).scrollTop()) {
this.style.background = 'lightseagreen';
sectionIndex = sections.indexOf(($(this).attr('id')));
}
});
now during scrolling you'll see which section is "current". This demonstrates the problem: after pressing "N" the previous section is still "current".
You can easily fix it:
currently the highlighted section is the one that intersects the upper bound of the screen,
instead, you can imagine a line a bit below top of the screen, like 50px lower, and consider that as the "focus point" that determines which section is current.
The code could look like this:
$('section').each(
function () {
const focus = $(document).scrollTop() + 50;
this.style.background = '';
if ($(this).position().top <= focus && ($(this).position().top + $(this).outerHeight()) > focus) {
this.style.background = 'lightseagreen';
sectionIndex = sections.indexOf(($(this).attr('id')));
}
});
Only change here is comparing against $(document).scrollTop() + 50 instead of $(document).scrollTop(). Notice that now the section becomes highlighted quicker, before it touches the top edge of the screen.

Change element CSS when a div is visible [duplicate]

This question already has answers here:
Remove CSS from a Div using JQuery
(13 answers)
Closed 7 years ago.
How to remove a CSS line of code when a certain div is reached?
Please note:
I need the CSS class that contains this line of code
The div is reached by clicking a link in the page header so I think mouseenter() event is not enough.
My Code:
$(document).ready(function(){
//firing the event to change CSS when reaching #resume
$('#resume').mouseenter(function() {
$('#resume').class('education').css('border-bottom','');
});
});
.education, .work {
margin-bottom: 48px;
padding-bottom: 24px;
//border-bottom: 1px solid #E8E8E8;
}
<section id="resume">
<!-- Education -->
<div class="row education">
<div class="three columns header-col">
<h1><span>Education</span></h1>
</div>
<div class="education work">
</div> <!-- main-col end -->
</div> <!-- End Education -->
When reaching #resume, you mean by scrolling? Then you need to use $(window).scroll() function / event:
$(function () {
// To change on scroll and reach `#resume`.
$(window).scroll(function () {
if ($(window).scrollTop() > $("#resume").offset().top)
$('#resume').addClass('education').css('border-bottom', '0');
});
// To change when hovering.
$('#resume').mouseenter(function () {
$(this).addClass('education').css('border-bottom', '0');
$(this).find(".education").css('border-bottom', '0');
});
});
just use the class name
$(document).ready(function(){
// firing the event to change CSS when reaching #resume
$('#resume').mouseenter(function(){
$('.education').css('border-bottom','');
});
The answer is on assumption that the class is already set on the element, and you just want to remove the border-bottom.
$(document).ready(function(){
//firing the event to change CSS when reaching #resume
$('#resume').mouseenter(function(){
//You can use 'this' as it is in the context of this element
//It will look inside the context element, then find all elements with class "education" and set the border-bottom to none.
$(this).find(".education").css({'border-bottom' : 'none'});
});
});
You could remove your class and add a new class containing the right css.
$(this).removeClass('someClass');
$(this).addClass('someClass');
Otherwise you could do something like this:
$(this).css({'border-bottom' : ''});
You can use 'this' when it is in the context of the element
$(document).ready(function() {
var Bind = function(elem, event, func) {
elem[window.addEventListener ? 'addEventListener' : 'attachEvent'](window.addEventListener ? event : 'on' + event, func, false);
},
scrollPos = function() {
var doc = document.documentElement;
return {
'left': (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0),
'top': (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0)
};
},
tgtOffset = document.getElementById('tgt').offsetTop,
scrolled = false,
spotted = function() {
var dist = tgtOffset - scrollPos().top,
adj = window.innerHeight > (480 / 2) ? window.innerHeight : 100;
return dist > -100 && dist < adj;
},
inView = null;
var res = document.getElementById('resume');
Bind(window, 'scroll', function(event) {
clearTimeout(inView);
if (!scrolled && spotted()) {
inView = setTimeout(function() {
res.classList.add('education');
});
}
});
});
.education,
.work {
margin-bottom: 48px;
padding-bottom: 24px;
// border-bottom: 1px solid #E8E8E8;
}
<section id="resume">
<!-- Education -->
<div class="row education">
<div class="three columns header-col">
<h1><span>Education</span></h1>
</div>
<div class="education work">
</div>
<!-- main-col end -->
</div>
<!-- End Education -->

Js on scroll event scroll to next/previous div

I'm trying to make a website scroll divs. When a visiter wants to scroll it should automatically go to the next or previous div.
Below you can see how my html looks like.
<body>
<header>
</header>
<div id="content">
<div id="contentv1">
</div>
<div id="contentv2">
</div>
<div id="contentv2">
</div>
<div id="contentv2">
</div>
<div id="contentv3">
</div>
</div>
</body>
I'm trying it with the following code:
(function() {
var scrollTo = function(element) {
$('html, body').animate({
scrollTop: element.offset().top
}, 500);
}
$('body').mousewheel(function(event) {
event.preventDefault();
var $current = $('#content > .current');
if ($current.index() != $('#content > div').length - 1) {
$current.removeClass('current').next().addClass('current');
scrollTo($current.next());
}
});
$('body').mousewheel(function(event) {
event.preventDefault();
var $current = $('#content > .current');
if (!$current.index() == 0) {
$current.removeClass('current').prev().addClass('current');
scrollTo($current.prev());
}
});
})();
The header has an height of 10% and sticks to the top. The content divs have a height of 90%. So when scrolled the top of the content divs should aline with the bottom of the header.
Can anyone help me into the right direction?

HTML / JS horizontal scrolling DIV "list"

What I want to make is an horizontally scrolling DIV "list" just like pretty much every big web site in the internet(netflix for example).
I tried to make it using a main DIV which would be some kind of container, a 2nd div which holds all the content and is inside the first DIV and a lot of DIVs, one for each content module, that go inside the 2nd div.
the parts of the 2nd DIV that overflow the main one should hide, and the content could be shown by moving it(the 2nd DIV).
this is the best I could come up with, but it still doesn't work jsfiddle
This is my HTML
<button onmouseover="left=1" onmouseout="left=0">
<</button>
<div class="container">
<div id="filler" style="left:0px">
<div class="module" style="background:coral;">testing</div>
<div class="module" style="background:lightblue;">testing</div>
<div class="module" style="background:lightgreen;">testing</div>
<div class="module" style="background:salmon;">testing</div>
<div class="module" style="background:lightyellow;">testing</div>
</div>
</div>
<button onmouseover="right=1" onmouseout="right=0">></button>
CSS
.container {
height:50px;
width:200px;
overflow:hidden;
}
#filler {
height:50px;
width:250px;
position:relative;
border-radius:10px;
background:crimson;
}
.module {
width:50px;
height:50px;
border-radius:5px;
float:left;
line-height:50px;
text-align:center;
}
JavaScript:
var feft = 0
//feft stands for filler left
var right = 0
var left = 0
var loaded = 0
window.onload=function(){
loaded=1
}
function move() {
if(loaded == 1){
if (left == 1 && feft <= 250) {
//left == 1 && feft <= filler width
document.getElementById("filler").style.left = feft + 1
}
if (right == 1 && feft >= 0) {
//right == 1 && feft >= 0
document.getElementById("filler").style.left = feft - 1
} //these IFs tests if the filler should move
feft = document.getElementById("filler").style.left
//this sets the feft variable to what it needs to be for the next run of the function
}}
window.setInterval(move(), 100)
I have made a fiddle for you.
demo
HTML code
<button onmouseover="left=1" onClick="move(-1)"><</button>
<div class="container">
<div id="filler" style="left:0px">
<div class="module" style="background:coral;">testing</div>
<div class="module" style="background:lightblue;">testing</div>
<div class="module" style="background:lightgreen;">testing</div>
<div class="module" style="background:salmon;">testing</div>
<div class="module" style="background:lightyellow;">testing</div>
</div>
</div>
<button onmouseover="right=1" onClick="move(1)">></button>
JS Code
var position = 0;
var moduleCount = document.querySelector(".module").length;
window.move = function(number) {
if (number) {
position += number;
if (number == 0 || number > moduleCount) {
position = 0;
}
} else {
if (position <= 4) {
position++;
} else {
position = 0;
}
}
moduleOffset = document.querySelector(".module").offsetWidth;
filler = document.querySelector("#filler");
filler.style.left = -( position* moduleOffset) + "px";
}
setInterval(window.move, 3000);
What you want to do is called "Carousel". I suggest to use bootstrap for example and implement it then in your site.
http://getbootstrap.com/javascript/#carousel
Try adding overflow: scroll as a CSS property to your container div.

Categories