Obtain id of current element in view - javascript

I have a list of items that are organized in an alphabetical order on a page. I would like to create a fixed element at the side of the page that shows, which letter section you are currently scrolling by.
For example, if you are scrolling past items starting with the letter 'D', the fixed div will show 'D'. I have been trying to create this with jQuery, but have been finding it tricky.
Each section has the class 'card-container' and an 'id' corresponding to the current letter.
ie.
<div id="a" class="card-container">
...
</div>
<div id="b" class="card-container">
...
</div>
<div id="c" class="card-container">
...
</div>
...
Any idea how I can accomplish this?
EDIT
So far I have this:
$(window).scroll(function() {
var winTop = $(this).scrollTop();
var letters = $('.card-container');
letters.each(function(section) {
if($(this).position().top <= winTop) {
console.log($(this).context.id);
$('.letter-show h3').text($(this).context.id);
}
});
});
So this seems to work, but I feel like it's not very performant. Any suggestions to improve on this?

As I said in the comment: There's not much you can do to improve your code - a few millisecond gain at most. Stuff like minimizing the DOM lookups and breaking the loop when the right element is found, dropping jQuery, etc... But I doubt you'd notice a difference even on the slowest machine you can find around.
var letters = $('.card-container');
var letterShow = $('.letter-show h3');
$(window).scroll(function() {
var winTop = $(this).scrollTop();
letters.each(function(section) {
if($(this).position().top <= winTop) {
letterShow.text($(this).context.id);
}
});
});
.card-container {height: 300px;border-top: 1px solid}
.letter-show {position: fixed}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="letter-show"><h3></h3></div>
<div id="a" class="card-container">
...
</div>
<div id="b" class="card-container">
...
</div>
<div id="c" class="card-container">
...
</div>
<div id="d" class="card-container">
...
</div>
<div id="e" class="card-container">
...
</div>

This is what did the trick:
$(window).scroll(function() {
var winTop = $(this).scrollTop();
var letters = $('.card-container');
letters.each(function(section) {
if($(this).position().top <= winTop) {
$('.letter-show h3').text($(this).context.id);
}
});
});

Related

How to hide an item?

var r1=Math.floor(Math.random()*255)
var g1=Math.floor(Math.random()*255)
var b1=Math.floor(Math.random()*255)
$(".color1").click(function (){
$(this).css("background", "rgb(" + r1 + "," + g1 + "," + b1 + ")")
})
$(document).ready(function () {
$(document).on('click', function (event) {
$target = $(event.target);
$target.addClass('clicked');
});
})
var numItems
var getfirstclass
var getsecondclass
$('div').click(function saveclassnames(){
var getfirstclass=$(this).attr('class')
console.log(getfirstclass)
var getsecondclass=$(this).attr('class')
console.log(getsecondclass)
getfirstclass===null
getsecondclass===null
})
$('div').click(function remove(){
var numItems = $('.clicked').length
if(numItems===2 && getfirstclass === getsecondclass){
$('.clicked').css('opacity', '0')
}
else{
$('.clicked').css('background', 'black')
}
})
<body>
<div class="container">
<div class="row">
<div class="color1"></div>
<div class="color2"></div>
<div class="color3"></div>
<div class="color4"></div>
</div>
<div class="row">
<div class="color5"></div>
<div class="color3"></div>
<div class="color1"></div>
<div class="color6"></div>
</div>
<div class="row">
<div class="color7"></div>
<div class="color6"></div>
<div class="color8"></div>
<div class="color5"></div>
</div>
<div class="row">
<div class="color7"></div>
<div class="color8"></div>
<div class="color4"></div>
<div class="color2"></div>
</div>
</div>
</body>
I am trying to make a game called "Memory" (if 2 flipped cards are same, the cards will disappear, but if the cards are not the same, they will flip back). But there is a difference between the original one). I am using random colors instead of card pictures, but I cannot make <div> elements with the same background-color disappear, or flip back if they are not the same. Can someone explain to me why this code does not work?
Thanks.
opacity: 0; hiding generates a lot of space although the element is not visible.
background: black; – the element needs to blend in with the background, otherwise it will not work (technically it won't work)
You can either do this:
$('yourItem').css({
display: 'none'
});
Or, the "simplest way to hide an element":
$('yourItem').hide();
For more information see https://api.jquery.com/hide/
You could use
display: none
If that messes with other stuff, use
visiblity: hidden;

jQuery: show/hide are instantaneous

I've one div that contains to other one:
<div>
<div id="card-container">....</div>
<div id="wait-for-result-container" style="display: none;">...</div>
</div>
On some event, I want to change the displayed element, with a fadeIn/fadeOut effect.
$('#card-container').hide(5000);
$('#wait-for-result-container').show(5000);
(I put some big number to really see the effect)
But when I trigger my effect, it is instantaneous, there is no fade-in/fade-out.
I'm not sure it matters, but I'm using jquery-3.1.1 and bootstrap 4 alpha.
Any idea what is going wrong?
EDIT
As asked, here is some clarification.
The element that I'm trying to hide is hided immediatly and the one I show is appearing immediately.
EDIT
I tried to put a demo here with the code from above:
$('#myBt').click(function(){
$('#card-container').hide(5000);
$('#wait-for-result-container').show(5000);
});
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<div>
<div id="card-container">First one</div>
<div id="wait-for-result-container" style="display: none;">Second one</div>
</div>
<button id="myBt">Click me</button>
If you can use the full version of jQuery, give jQuery fadeOut and fadeIn a try :)
$('#myBt').click(function(){
var duration = 5000;
$('#card-container').fadeOut(duration);
$('#wait-for-result-container').delay(duration).fadeIn(duration);
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div>
<div id="card-container">First one</div>
<div id="wait-for-result-container" style="display: none;">Second one</div>
</div>
<button id="myBt">Example1</button>
If you have to stick with the slim version, you can use setInteval
$('#myBt').click(function(){
var duration = 5000;
var op = 0.9; // initial opacity
var timer1 = setInterval(function () {
if (op <= 0.1){
clearInterval(timer1);
op = 0;
$('#card-container')[0].style.display = 'none';
}
$('#card-container')[0].style.opacity = op;
op -= 100/duration;
}, 100);
var timer2 = setInterval(function () {
if (op <= 0){
$('#wait-for-result-container')[0].style.opacity = 0;
$('#wait-for-result-container').show();
}
if (op >= 1){
clearInterval(timer2);
}
if($('#wait-for-result-container').is(':visible')){
$('#wait-for-result-container')[0].style.opacity = op;
op += 100/duration;
}
}, 100);
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div>
<div id="card-container">First one</div>
<div id="wait-for-result-container" style="display: none;">Second one</div>
</div>
<button id="myBt">Example2</button>

Remove Link on scroll

In my application I have 4 links with different IDs and 4 DIV with same ID as each link (I use them for anchor-jumping).
My current code:
One
Two
Three
Four
<div class="col-md-12 each-img" id="1">
<img src="img/album-img.png">
</div>
<div class="col-md-12 each-img" id="2">
<img src="img/album-img.png">
</div>
<div class="col-md-12 each-img" id="3">
<img src="img/album-img.png">
</div>
<div class="col-md-12 each-img" id="4">
<img src="img/album-img.png">
</div>
Sometime users just scroll to second div id="2" first before they click on buttons and when they do so, they are sent to top id="1" first instead of continue to next ID id="3".
Only one button is visible at a time with use of CSS and when link is clicked, I remove that link.
CSS
a.btn{display: none}
a.btn a:first-child{display: block !important;}
jQuery
$(document).ready(function(){
$('a.btn').click(function () {
$(this).remove(); // remove element which is being clicked
});
});
How can I achieve so if user scroll down, each link that has same ID as the DIV get removed.
For instance: If user scroll down to <div class="col-md-12" id="1">, One gets removed and Next link would be Two to click on.
PS: This is for a dynamic page and IDs will change, so we need another selector maybe
This is what I have tried until now, but problem is that it removes all the links and not first one only
$(function() {
var div = $('.each-img').offset().top;
$(window).scroll(function() {
var scrollTop = $(this).scrollTop();
$('.each-img').each(function(){
if (scrollTop >= div) {
$("a.btn:eq(0)").remove();
//$("a.btn:first-child").remove();
}
});
});
});
PS: The way HTML & CSS is setup doesn't need to like this and I can change it to whatever that will be better for the function
It's no problem to make it dynamic:
JSFiddle: https://jsfiddle.net/rc0v2zrw/
var links = $('.btn');
$(window).scroll(function() {
var scrollTop = $(this).scrollTop();
links.each(function() {
var href = $(this).attr('href');
var content = $(href);
if (scrollTop > content.offset().top) {
$(this).hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="position:fixed; top:0; left:0; right:0">
One
Two
Three
Four
</div>
<div class="col-md-12" id="1">
<img src="http://lorempixel.com/400/500/">
</div>
<div class="col-md-12" id="2">
<img src="http://lorempixel.com/450/500/">
</div>
<div class="col-md-12" id="3">
<img src="http://lorempixel.com/480/500/">
</div>
<div class="col-md-12" id="4">
<img src="http://lorempixel.com/500/500/">
</div>
I think this is more or less what you're after:
JSFiddle
https://jsfiddle.net/wc0cdfhv/
It's good to cache the position of your elements outside the scroll function, this way it doesn't need to be calculated every time.
You should also keep in mind this won't scale too well if you have dynamic content but if you're just working with 4 static links it will do fine.
Code
$(function() {
var scroll1 = $('#1').offset().top;
var scroll2 = $('#2').offset().top;
var scroll3 = $('#3').offset().top;
var scroll4 = $('#4').offset().top;
$(window).scroll(function() {
var scrollTop = $(this).scrollTop();
if (scrollTop >= scroll4) {
$("#go1, #go2, #go3, #go4").hide();
}
else if (scrollTop >= scroll3) {
$("#go1, #go2, #go3").hide();
$("#go4").show();
}
else if (scrollTop >= scroll2) {
$("#go1, #go2").hide();
$("#go3, #go4").show();
}
else if (scrollTop >= scroll1) {
$("#go1").hide();
$("#go2, #go3, #go4").show();
}
else {
$("#go1, #go2, #go3, #go4").show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="position:fixed; top:0; left:0; right:0; background:#CCC">
One
Two
Three
Four
</div>
<div class="col-md-12" id="1">
<img src="https://www.myoodle.com/images/easyblog/616/2014042_Therapy_Dog_003.jpg">
</div>
<div class="col-md-12" id="2">
<img src="https://www.myoodle.com/images/easyblog/616/2014042_Therapy_Dog_003.jpg">
</div>
<div class="col-md-12" id="3">
<img src="https://www.myoodle.com/images/easyblog/616/2014042_Therapy_Dog_003.jpg">
</div>
<div class="col-md-12" id="4">
<img src="https://www.myoodle.com/images/easyblog/616/2014042_Therapy_Dog_003.jpg">
</div>
use scrollEvent listener
$(window).scroll(function(e){
if($(this)).scrollTop >= $('div#1').offset().top){
$("a#1").hide();
}
});
Use Something like that and it will work .. Hope this helps

looking for a good pratice to hide and display some divs

Hello everybody I would like to hide some divs and display others when I click on a specifiks links.
Actually I did like this :
<html>
<head>
<script>
function loadA(){
document.getElementById("A").style.display="block";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="none";
}
function loadB(){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="block";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="none";
}
function loadC(){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="block";
document.getElementById("D").style.display="none";
}
function loadD(){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="block";
}
</script>
</head>
<body>
<div class="menu">
A
B
C
D
</div>
</body>
</html>
This is work with me but as you see it's not a good practice and sure there is another way better than this , can you show me please !
A solution without javascript:
.container > div{
display:none
}
.container > div:target{
display:block
}
<div class="menu">
<a href="#A" >A</a>
<a href="#B" >B</a>
<a href="#C" >C</a>
<a href="#D" >D</a>
</div>
<div class="container">
<div id="A" >A content</div>
<div id="B" >B content</div>
<div id="C" >C content</div>
<div id="D" >D content</div>
</div>
https://developer.mozilla.org/en-US/docs/Web/CSS/%3Atarget
https://css-tricks.com/css3-tabs/
You can create one function and reuse it for each element:
function loadDiv(id){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="none";
document.getElementById(id).style.display="block";
}
And pass the correct id into each onclick:
<div class="menu">
A
B
C
D
</div>
Here's how you should do it. No inline javascript, handling click events with an eventListener and wrapping all elements together with a class, making it much less code to write and maintain:
JS:
function divLoader(e){
var hide = document.getElementsByClassName("hideAndShow");
for (var i = 0; i<hide.length;i++) {
hide[i].style.display="none";
}
document.getElementById(e.target.getAttribute('data-link')).style.display="block";
}
var anchors = document.querySelectorAll('.menu > a');
for (var i = 0; i<anchors.length; i++) {
anchors[i].addEventListener('click',divLoader);
}
HTML:
<div class="menu">
A
B
C
D
</div>
<div id="A" class="hideAndShow" style="display:none;">A</div>
<div id="B" class="hideAndShow" style="display:none;">B</div>
<div id="C" class="hideAndShow" style="display:none;">C</div>
<div id="D" class="hideAndShow" style="display:none;">D</div>
In such cases where you have similar repetitive code you can use a common technique called "Abstraction". The main idea is the turn the common code into parameters of a single function in your case it would be:
function loadByID(id){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="none";
document.getElementById(id).style.display="block";
}
However this is also still a little bit redundant, for larger menus and displaying multiple links you can do something like
function loadByIDs(ids){
var links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++){
document.getElementById(links[i].id).style.display = none;
}
for each(var id in ids){
document.getElementById(id).style.display = block;
}
}
This will work much better when you have too much links and want to display more than one link at a time (so you will need to pass in an array)
Note: If you are using Jquery you can just use .each() function to get rid of the first for loop
Hope this helps!
I think the best practice in your case is to define a general function that work however the number of links with specific class in my example the class is link, take a look at Working Fiddle.
Now your script will work with dynamic links added in div, you have just to add html without touching the js will detect change.
HTML :
<div class="menu">
A
B
C
D
</div>
JS :
load = function(e){
//select all links
var links = document.getElementsByClassName('link');
//Hide all the links
for (i = 0; i < links.length; i++) {
links[i].style.display = "none";
}
//Show clicked link
e.target.style.display = "block";
}
Hope this make sens.
HTML
<body>
<div id="main">
<ul id="nav">
<li>Home</li>
<li>About Us</li>
</ul>
<div id="container">
<div id="wrapper">
<div class="content">
<div id="menu_home">
<h2>Menu 1</h2>
</div>
<div id="menu_about">
<h2>Menu 2</h2>
</div>
</div><!--content-->
</div><!--wrapper-->
</div><!--container-->
</div><!-- main-->
</body>
JS
$(document).ready(function(){
$("#menu_home").slideUp("fast");
$("#menu_about").slideUp("fast");
$("#menu_home").show();
$("#nav a").click(function(){
var id = $(this).attr('id');
id = id.split('_');
$(".content div").slideUp("fast");;
$(".content #menu_"+id[1]).slideToggle("fast");
});
});
Here is the example
function loadA()
{
document.getElementById("A").style.visiblity="show";
document.getElementById("B").style.visiblity="hide";
document.getElementById("C").style.visiblity="hide";
document.getElementById("D").style.visiblity="hide";
}
if visibility dont work,just change the visibility keyword with visible and hide with hidden.
and one more thing,u should not write function for each div..what can u do just pass id of a div which u want to show and hide others..see below
function trigger(id)
{
var alldiv={"A","B","C","D"};
for(i=0;i<alldiv.length;i++)
{
if(alldiv[i]==id)
document.getElementById(id).style.visiblity="show";
else
document.getElementById(alldiv[i]).style.visiblity="hide";
}
}

jquery and event scroll

i have 1 class html with various elements i want add a class new class in first element that scroll top reach the top ofos this elements, then when the scroll reach the second add in second too and so on. i tried this
var element = $(".element");
$(window).scroll(function () {
var scroll = $(window).scrollTop();
for(var i = 0; i < element.length;i++){
if(scroll > element.eq(i)){
element.eq(i).addClass("newClass");
}
}
})
html piece
<div>
<div class="element">
<img src="img/image1" />
</div>
<div class="element">
<img src="img/image2" />
</div>
<div class="element">
<img src="img/image3" />
</div>
</div>
but this line element.eq(i).addClass("newClass") dont work :) how i should to do
try to use
if(scroll > element.eq(i).offset().top - ($(window).height() / 2) ){
element.eq(i).addClass("newClass");
}
DEMO

Categories

Resources