how to make class disappear when scrolling up in jquery - javascript

I am trying to find out how to make a class disappear when scrolling up in a browser. I had been able to make a class to appear when a certain height in a browser is met by using this code.
jQuery(".tetapElement").css("opacity", 1);
jQuery(window).scroll(function() {
var windowHeight = jQuery(window).height();
if (windowHeight < 470) {
jQuery(".tetapElement").css("opacity",1);
} else if (windowHeight > 1820) {
jQuery(".tetapElement").css("opacity",1);
}
else {
jQuery(".tetapElement").css("opacity",0);
}
});
.tetapElement {
position:fixed;
top: -30%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--make another checkout button -->
<div class="tetapElement">
<div class="order_title">Order details:</div>
<div class="order_bar_details">
<div class="pack_name"><?php echo $post->post_title ;?></div>
<div class="pack_name_value">Package name:</div>
<div class="pack_details"></div>
<div class="addon_title">Add-On Menu</div>
<div class="addon_details"></div>
</div>
<div class="order_price">Total price (<?php echo $currency; ?>): <span class="total_price">0</span></div>
<div class="chekout_link">
<textarea id="order_details" style="display:none;" name="order_details" ></textarea>
<?php wp_nonce_field('process_checkout_action','process_checkout_field'); ?>
<input type="submit" class="btn btn-success checkout_btn mk-flat-button shop-black-btn" value="Checkout">
</div>
</div>
you can see it in action in here. so that when you click on that link and reduce your browser height then another class would pop up. But I need to finds way how to make that class to disappear again when a user scroll up so as not to disturb another class that were put there.
so in essence, I put 2 class. one class will disappear when scrolling down and then replace by another class and I want this another class to disappear also when a user scroll up and replace by original class. any idea how to that in jquery?

A very similar question is asked here.
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st < lastScrollTop){
// upscroll code
$(".tetapElement").removeClass("classToRemove");
}
lastScrollTop = st;
});

media query max-height seems to be a better solution if you want to alter css properties in my opinion

Related

Separating content within div with Jquery

I have the following HTML:
<div class="page">
<div class="somecontent_1">...</div>
<div class="somecontent_2">...</div>
<div class="somecontent_3">...</div>
<div class="somecontent_4">...</div>
</div>
Now I'd like to separate the content with a separate page so it looks something like this:
<div class="page">
<div class="somecontent">...</div>
<div class="somecontent">...</div>
</div>
<div class="newpage">
<div class="somecontent">...</div>
<div class="somecontent">...</div>
</div>
The function checks the height of each class somecontent and if it's larger than a certain amount, I need to move the content to a new page.
My guess is that I would need to create an empty div (newpage) and then fetch the elements after the height is exceeded and move them to the empty newpage and continue iterate like that.
My question would be how I would get all content that are after the last element that reached the height so I can move it to the new empty page that I would create. Other solutions are most welcome if there is a better way of doing it!
The code I came up with looks like this:
var page = $('.page');
var pageHeight = 0;
$.each(page.find('.somecontent'), function() {
if (pageHeight > 1000) {
page.next('<div class="newpage"></div>');
/* Somehow get all elements to add to the newly created page */
page.next('.newpage').append(<NEXT_ELEMENTS>);
pageHeight = 0;
}
pageHeight = pageHeight + $(this).height();
});
When you reach the page which answers the height criterion use the .nextAll function to get all the next siblings of it, then use .wrapAll to wrap them with your newpage div.
Here is the corresponding documentation of nextAll and wrapAll, it has everything you need to cover your scenario.
See comments in line below.
// Instead of the $.each() utiility function
// Just loop over each content area that needs
// examination
$('.somecontent').each(function(index, item) {
// Check if the height of the item is greater than the target (20px for this example)
if (parseInt(getComputedStyle(item).height,10) > 20) {
// Make a new div after the div that the item is currently in
// if one doesn't already exist
if($(".newpage").length === 0){
$(item.closest(".page")).after('<div class="newpage"></div>');
}
// Move the item into the new div
$(item.closest(".page")).next('.newpage').append(item);
}
});
//console.log(document.body.innerHTML); // shows resulting HTML
div.page {border:1px solid red; }
div.newpage {border:1px solid green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page">
<div class="somecontent">This<br>is<br>some<br>content</div>
<div class="somecontent">This is some content</div>
<div class="somecontent">
<ul>
<li>This</li>
<li>is</li>
<li>some</li>
<li>content</li>
</ul>
</div>
<div class="somecontent">Other</div>
</div>

addClass are added to all DIV's regardless of their position (viewport)

I've searched a solution for my problem but I didn't find any answer for that.
here is the problem, I'm using animate.css for many DIVs but I want the animations take effect when the element -which has classes 'animated' and 'animation in animate.css'- is in viewport. My problem is that classes 'animated' and 'animation in animate.css' are added to all my DIV's whatever the position is.
the script
$(function() {
"use strict";
$(window).scroll(function() {
addClassToElementInViewport($('div.accueilText'), "slideInleft");
addClassToElementInViewport($('div.ateHT'), "slideInLeft");
});
function addClassToElementInViewport(element, newClass) {
if (isVisible(element)) {
element.removeClass('hidden');
element.addClass(newClass);
}
}
function isVisible($el) {
var winTop = $(window).scrollTop();
var winBottom = winTop + $(window).height();
var elTop = $el.offset().top;
var elBottom = elTop + $el.height();
return ((elBottom<= winBottom) && (elTop >= winTop));
}
});
html code
<div class="container">
<div class="row text-center accueilText hidden animated">
<div class="col-md-6 col-md-offset-3">blablabla bla bla<br>bla<br>blabla bla </div>
</div>
<hr>
<div class="row">
<div class="col-lg-12"><center><img class="img-responsive" src="Images/verin_hydroseb.png" alt="Hydroseb logo"></center></div>
</div>
</div>
<div class="row">
<div class="text-justify col-sm-5 ateHT hidden animated"> <br>bla bla blabllabla </div>
<div class="col-sm-5 col-sm-offset-2 ateHI hidden animated"> <img class="img-responsive" src="Images/atelier_hydraulique.png" alt="HydroSeb Hydraulique"></div>
</div>
I really appreciate any help you can provide :)
$('div.accueilText') this will find all divs with class accueilText
But i feel you may be looking for this.
First of all on-screen visible area is known as Viewport.
(image is taken from OP. Cleared and edited in Photoshop)
So all you need is to detect all elements in your Viewport.
This can be achieved using many plugins for jQuery, but I'll explain you on one example, which is called as jQuery withinviewport
Link to source and documentation on: [ withInViewport - Github ]
Step 1:
Download plugins and include jQuery framework and withinviewport plugin in your script:
<script src="http://code.jquery.com/jquery-1.7.min.js"></script>
<script src="withinViewport.js"></script>
<script src="jquery.withinviewport.js"></script>
.
Step 2:
Initialise function on scroll event:
$(window).bind("scroll", function() {
//your code placeholder
});
.
Step 3:
Use withinviewport selector to get all elements in you Viewport and by each element add class to corresponding list-item in your #timeline container:
$("#elements > div").withinviewport().each(function() {
$('#timeline > li[view-id="'+$(this)[0].id+'"]').addClass('active');
});
Step 4:
Put all together:
$(window).bind("scroll", function() {
//clear all active class
$('#timeline > li').removeClass('active');
//add active class to timeline
$("#elements > div").withinviewport().each(function() {
$('#timeline > li[view-id="'+$(this)[0].id+'"]').addClass('active');
});
});
.
.
Also this plugin gives you opportunity to set top, bottom, left and right offset for view-port.
See demo here: http://patik.com/code/within-viewport/

Highlight active div after scroll

Is there an easy way to highlight a top with id (apply css-class with specific color f.e.) after user scrolls to it? I have a scrollspy on page, but it seems that plugin will not help me, so I can't make to ends meet.
P.S. I didn't find alike info in Google or StackOverflow, so please, don't get me wrong.
There is a rough example of page
https://jsfiddle.net/masyurik/kdnzdeb2/#&togetherjs=DeaMiBADpp
HTML
<div id="secA" class="section">
Hello it's secA
<div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
</div>
<div id="secB" class="section">
Hello it's secB
<div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
</div>
<div id="secC" class="section">
Hello it's secC
<div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
</div>
CSS
.section {
background-color: red;
}
.active {
background-color: yellow;
}
You need to use scrollevent and change the class accordingly... kindly check https://jsfiddle.net/77v3329y/1/
jQuery
$(document).ready(function() {
var a = +$('#secA').height();
var b = $('#secB').height();
var c = $('#secC').height();
console.log(a);
console.log(b);
console.log(c);
$(window).on('scroll', function() {
$('#secA, #secB, #secC').removeClass('active');
var st = $(document).scrollTop();
if (st < a) {
$('#secA').addClass('active');
}
if (st > a) {
$('#secB').addClass('active');
}
if (st > a + b) {
$('#secC').addClass('active');
}
})
});
You can use jquery-waypoints to know which element has reached at top of the viewport. The plugin will give you the callback which will help you to change the css of the active element.
Here is the solutions to detect the scroll to top event.
Fire event when div is visible to visitor with jQuery?
Simply use jQuery to change the css of the element when scroll to top: $("#secA").css("background-color", "yellow");

Dynamically set scroll coordinates & change DOM element with 200px scroll tolerance from these coordinates

I've got a single page site with two div modules that expand when clicked.
The first is at the top, in the Hero section and with the current code works as desired. The second is much further down the page in another section. Currently this second module closes as soon as the scroll takes place.
What I need to do is get the documents scroll coordinates when the div is clicked. Then once the user scrolls 200px up or down the div closes back up. Regardless of where it (the div) is on the site.
All the questions I found here and elsewhere only refer to setting the scroll tolerance relative to the window position on page load. But for me that's no goon. This site is responsive, and as it changes the initial positions of the div's will / can be unknown. I need someway of dynamically storing the viewports scroll position when the div's are clicked and assigning the 200px tolerance then.
I hope that makes sense. I've been at this for like 12+hrs now. SOS :)
Here's the Fiddle
If you don't want to go over to Fiddle, Here's the requisite code
HTML:
<body>
<section id="hero">
<div>
<div class="module-cta hero-cta">
<a class="module-cta__button"><!-- Fallback location -->
<span class="module-cta__text">PRESS ME</span>
</a>
<div class="module-cta__open">
<div class="module-cta__open-inner">
<div class="hero-cta__contact-points">
<div class="phone">
<div class="hero-cta_contact_logo">
<span><!-- phone.svg" --></span>
</div><!-- .service-logo -->
<div class="contact_trigger">
<a>Scroll down to 200px to see</a>
</div><!-- .contact_trigger -->
</div><!-- .phone -->
<div class="email">
<div class="hero-cta_contact_logo">
<span><!-- email.svg --></span>
</div><!-- .service-logo -->
<div class="contact_trigger">
<a>this div fold back up</a>
</div><!-- .contact_trigger -->
</div><!-- .email -->
</div><!-- .hero-cta__contact-points -->
<button class="module-cta__close module-cta__cancel"><i class="icon"><span></span></i></button>
</div><!-- .hero-cta__open-inner -->
</div><!-- .hero-cta__open -->
</div><!-- .hero-cta -->
</div>
</section>
<section class="spacer"></section>
<section id="service_area">
<div class="area_input">
<div class="module-cta area-cta wow fadeInUp" id="form_module">
<a class="module-cta__button area-cta__button">
<span class="module-cta__text area-cta__text">NOW PRESS ME</span>
</a>
<div class="module-cta__open area-cta__open">
<div class="module-cta__open-inner area-cta__open-inner">
<div class="area-cta__search">
<form class="postcode_form" id="postcode_form" name="postcode_form" action="#">
<input type="number" id="your_postcode" class="your_postcode" name="postcode" placeholder="3???">
<button type="button" class="area-btn"><span></span></button>
<a class="call-now">##########</a>
</form>
</div><!-- .area-cta__search -->
<button class="module-cta__close module-cta__cancel"><i class="icon"><span></span></i></button>
</div><!-- .area-cta__open-inner -->
</div><!-- .area-cta__open -->
</div><!-- .area-cta -->
</div><!-- .area_input -->
</section>
<section class="spacer"></section>
</body>
Script:
I'm sure a lot of this can be cleaned up and shrunk, but for now I'm just trying to get it all going.
// opens & closes modules by clicking module name
$('.module-cta__button').on('click', function(){
if($(this).parent().hasClass('hero-cta')){
$(this).parent().toggleClass('module-cta--active');
} else {
if($(this).parent().hasClass('area-cta')){
$(this).parent().toggleClass('module-cta--active');
}
}
});
// closes modules with .module-cta__close btn
$('.module-cta__close').on('click', function(){
if($(this).closest('div .module-cta').hasClass('module-cta--active')){
$(this).closest('div .module-cta').removeClass('module-cta--active');
}
});
// closes modules on scroll.
// * works but doesn't apply scroll tolerance of 200px for #area
$(window).scroll(function(){
var currentPos = $(window).scrollTop();
var module = $('div .module-cta');
if(module.hasClass('module-cta--active') && module.position().top <= currentPos+200){
$('div .module-cta--active').removeClass('module-cta--active');
}
});
// closes modules when escape key is pressed
$(window).keydown(function(escape){
var key = escape.which;
if(key == 27){
$('div .module-cta--active').removeClass('module-cta--active');
}
});
see Fiddle for css
Thanks for any help or useful suggestions in advanced.
I've put together a much smaller and simpler demonstration, just to show you what variables you need to accomplish this. Essentially, when a div is clicked, capture the current document scroll position using $(document).scrollTop(). Also store a refference to the current div that has been clicked.
When scrolling, check the difference between the current scroll and the new scroll, and using your clicked div reference, shrink the div when the difference is 200 or greater. JS fiddle below;
https://jsfiddle.net/jLqu4pas/
Code from Fiddle;
var currentScroll;
var lastClickedDiv;
$('section').click(function(){
$(this).css({'height' : '400'})
currentScroll = $(document).scrollTop();
lastClickedDiv = $(this);
console.log(currentScroll);
})
$(window).scroll(function(){
if($(document).scrollTop() > currentScroll + 200){
lastClickedDiv.css({'height' : 0})
}
})
So I've put together a script that will potentially help you.
I've done some basic testing on it, but if you come across any problems make a comment.
// Generate offsets and return them as an object
function generateOffsets($element, tolerance)
{
var offsets = $element.offset(),
offsetTop = offsets.top;
return {
scrollPos: offsetTop,
toleranceTop: offsetTop - tolerance,
toleranceBottom: offsetTop + tolerance
};
}
// Run a callback when the user leaves the scroll tolerance of a set of elements
function closeOnScroll($elements, tolerance, callback)
{
$elements.each(function() {
var $element = $(this),
offsets = generateOffsets($element, tolerance),
resizeEvent;
// On resize, regenerate the offsets so they stay up to date
$(window).on('resize', function(e) {
resizeEvent = e;
offsets = generateOffsets($element, tolerance);
});
// On scroll check if we've left the tolerance area, if so run the event and unbind
$(window).on('scroll', function(e) {
var windowPos = $(this).scrollTop();
if (windowPos < offsets.toleranceTop || windowPos > offsets.toleranceBottom) {
callback($element);
$(this).unbind(e);
$(this).unbind(resizeEvent);
}
});
});
}
// Example: Apply the event to a set of elements
$('.btn').click(function() {
closeOnScroll($('div .module-cta'), 200, function($element) {
$element.removeClass('module-cta--active');
});
});
The thing to remember with thie script is that it needs to be applied EVERY time the user clicks your button. You may say, WHY WOULD YOU DO THAT - but it actually has some serious performance implications.
The events rely on both scroll and resize, both of which are very slow, especially if not debounced like in this script. However, what I do in the script is unbind the events once it has occured. Otherwise, the resize and scroll would keep happening for each and every one of your buttons until the end of time. By 'unbinding' the event, you ensure long running performance of your page.
Wouldn't want to ruin those pretty animations would we?

How to get DIV ID on click

I am new to javascript and couldnt find answer online (I feel like its out there since this seems pretty simple thing, I might not be using the right search terms though)
I am working with the code in this jfiddle:
http://jsfiddle.net/ApoG/f7qqq6k2/4/
$('.item').click(function(){
if( document.getElementById("one").style.display != "none") {
document.getElementById("one").style.display = "none";
} else {
document.getElementById("one").style.display = "block";}
var $this = $(this),
tileStyle = $this.hasClass('big') ? { width: 50, height: 50} : { width: 170, height: 110};
$this.toggleClass('big');
$this.find('.item-content').stop().animate( tileStyle );
$container.isotope( 'reLayout' )
});
When you click a div, it takes the 'item' class and changes its properties.
My goal is to have image or one type of text in a widget when its small and another text or image when its expanded on click. I am going to achieve that by changing div custom properties when its clicked using an if statement in my javascript. (right now testing with changes to display)
My questions is...since 'item' class is selected on click, how can I get the DIV ID on click? (right now I hard coded div id)
Thank you.
With JQuery:
$('div').click(function(){
alert(this.id);
});
JSFiddle Demo, with your full code
With Pure JS:
var div = document.getElementsByTagName("div");
for(var i=0; i<div.length; i++){
div[i].onclick = function(){
alert(this.id);
}
}
JSFiddle Demo
Thank you for the toggle tip. I used that to make my code work and show different things in the box depending on the click of the div.
Here is what I ended up doing:
https://jsfiddle.net/ApoG/z3x6hqLe/
<script>
function toggleText1() {
$('#one_one').toggle();
$('#one_two').toggle();
}
function toggleText2() {
$('#two_one').toggle();
$('#two_two').toggle();
}
</script>
<div id="container">
<div class="item">
<div id=one style=display:"none" class="item-content" onclick="toggleText1()">
<div id=one_one class="text" >Show More</div>
<div id=one_two class="text" style="display:none">Show Less</div>
</div>
</div>
<div class="item">
<div id=two style=display:"none" class="item-content" onclick="toggleText2()">
<div id=two_one class="text" >Show More</div>
<div id=two_two class="text" style="display:none">Show Less</div>
</div>
</div>
<div class="item">
<div id=three style=display:"none" class="item-content"></div>
</div>
</div>
I am definitely sure there is a more optimal way to define all the toggle but as I mentioned earlier I am a complete newb so hopefully with more tinkering I will figure that one out.

Categories

Resources