jQuery offset not working as expected - javascript

I am getting the value of an data-anchor for each "li" I click on and I use it to match the id value of list of divs
<div id="rateCardsContainer">
<div id="one"><div>
<div id="two"><div>
</div>
I am than using the following function so that when I click on li that has the same id as div than the div will scroll to the top:
AIG.RC.setModalEventsListener = function() {
$(AIG.RC.LIST_NODE).on('click', 'li', function() {
var currentID = $(this).attr('data-anchor');
var currentOffset = $('#' + currentID).offset().top;
console.log(currentOffset);
$('#rateCardsContainer').animate({scrollTop:currentOffset}, 500);
});
};
This "console.log(currentOffset);" returns very odd values as you can see.I click on the list on the left and the corresponding div on the right with same id should scroll to the top, however it has very irregular scrolls

Related

Updating underline-slider position on resize

I have an underline slider for my navigation links that get the specific width and position based on the clicked element, <li>, using the getBoundingClientRect(). This works as expected, but on resizing the browser window I would like to update the underline-slider's position.
As it is right now I'm only grabbing the width and position of the first <li>. What I need and want to do is to target the specific <li> that currently has the underline-slider and update its width and position on resizing so the slider follows along during resize with the right <li> element.
Any tip how I could grab the currently active <li>??
This is the codepen where I have the example in where I only grab the first <li> everytime on resize:
https://codepen.io/Shenden/pen/PELbOM
the script looks like this:
const lists = document.querySelectorAll('.dropdown > li');
const slider = document.querySelector('.slider');
function handleEnter() {
// from current li
const dropCoords = this.getBoundingClientRect();
//get the current li's width and height
//apply coords of li's to the slider-div elem
slider.style.setProperty('opacity', '1');
slider.style.setProperty('width', `${dropCoords.width}px`);
slider.style.setProperty('transform', `translate(${dropCoords.left}px)`);
}
//for each li-elem clicked trigger handleEvent function
lists.forEach(listLink => listLink.addEventListener('click', handleEnter));
window.addEventListener('resize', function(){
const elem = document.querySelector('.dropdown > li').getBoundingClientRect();
slider.style.setProperty('transform', `translate(${elem.left}px)`);
slider.style.setProperty('width', `${elem.width}px`);
});
You could keep track of which item should be active by flagging it with a class like this :
const lists = document.querySelectorAll('.dropdown > li');
const slider = document.querySelector('.slider');
function handleEnter() {
//remove active item indicator class if it is present
document.querySelector(".activeItem").classList.remove("activeItem");
//add the active item indicator class to the current item
this.classList.add("activeItem");
//perform the move code for the underline
const dropCoords = this.getBoundingClientRect();
//get the current li's width and height
//apply coords of li's to the slider-div elem
slider.style.setProperty('opacity', '1');
slider.style.setProperty('width', `${dropCoords.width}px`);
slider.style.setProperty('transform', `translate(${dropCoords.left}px)`);
}
//for each li-elem clicked trigger handleEvent function
lists.forEach(listLink => listLink.addEventListener('click', handleEnter));
window.addEventListener('resize', function(){
//select the correct item using the activeItem indicator class
const elem = document.querySelector('.dropdown > li.activeItem').getBoundingClientRect();
slider.style.setProperty('transform', `translate(${elem.left}px)`);
slider.style.setProperty('width', `${elem.width}px`);
});
CodePen fork : right here

How to clone and place two different items in jquery in the respective positions

I have a div and a button to close that div. I am cloning them both separately and assigning a unique incrementing id to both. Everything is working in that the cloning happens and the button closes the Div.
I have a problem though regarding the placement of the button. I want the button to always be in the same position with reference to its cloned div. Any ideas how to do this?
HTML
X
<div id="id"></div>
Add
Javascript
function duplicateDiv(){
$('#btn').clone().attr('id', 'btn'+ cloneCount2++).insertBefore($('[id^=id]:first'));
$('#id').clone().attr('id', 'id'+ cloneCount++).insertAfter($('[id^=id]:first'));
//clearing the input items in the new cloned div
$("#id").find("input").val("");
}
function hideDiv(obj){
var currentId = $(obj).attr('id');
var divId = currentId.replace("btn", "id");
$("#"+divId).hide();
$("#"+currentId).hide();
}
If interpret Question correctly , try using .appendTo() , .insertAfter($("#btn" + cloneCount))
var cloneCount = 0, cloneCount2 = 0;
function duplicateDiv() {
//the close button
$("#btn")
.clone().attr("id", function(_, id) {
return id + (++cloneCount2)
})
.appendTo("body")
$("#id")
.clone().attr("id", function(_, id) {
return id + (++cloneCount)
})
.insertAfter($("#btn" + cloneCount))
//clearing the input items in the new cloned div
$("#id").find("input").val("");
}
function hideDiv(obj) {
var currentId = $(obj).attr('id');
var divId = currentId.replace("btn", "id");
$("#" + divId).hide();
$("#" + currentId).hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
X
<div id="id">div</div>
Add
One of the way is Jquery Offset
var destination = $('.original-content').offset(); // get position of original
$('.original-content').hide(); // hide original
$('.cloned-content').css({top: destination.top, left: destination.left}); // set position of cloned

How to obtain in jQuery a list of elements ordered by position?

In this plunk I have these three (draggable) divs that can be positioned anywhere on the screen. What I need is to obtain, after the divs were dragged around, the order based on their left position (i.e. the left-most div should appear first in the list). How to achieve this in jQuery? In my attempt I always get the original order.
HTML
<p>Drag around the divs, then <button id="b1">click</button> to obtain the order (based on each left position)</p>
<div id="div1"
style="width:60px;height:60px;background-color:orange;margin:20px;float:left">1</div>
<div id="div2"
style="width:60px;height:60px;background-color:yellow;margin:20px;float:left">2</div>
<div id="div3"
style="width:60px;height:60px;background-color:pink;margin:20px;float:left">3</div>
Javascript
$('#div1').draggable();
$('#div2').draggable();
$('#div3').draggable();
$('#b1').click(function() {
var i = 1;
var divs = $('div');
divs.each(function () {
var div = $(this);
alert(div.text() + ' is number ' + i);
i++;
});
});
You can use the jQuery.prototype.offset and Array.prototype.sort methods. The following snippet sorts the collection based on the left position of the elements:
$('#b1').click(function() {
$('div').sort(function(a, b) {
return $(a).offset().left > $(b).offset().left;
}).each(function (i) {
var div = $(this);
alert(div.text() + ' is number ' + ++i);
});
});

scrollTop to active element in a overflow scroll div

I have a specific question about .scrollTop. I have a div with a specific height and a lot of p tags inside:
<div id="scroll">
<p>name1</p>
<p>name2</p>
<!-- till name50 -->
</div>
depending on the name you click it gets a class .active. What I then want to do is scroll the div so, that the name is at the top. So what I get is that I can use scrollTop in an animate function like this:
$('#scroll').animate({scrollTop: value });
but how can I get the var value. I tried it with
var value = $('#scroll p').hasClass('active').position().top;
But somehow it does not work.
Some help is much appreciated.
You need to check scrollTop() for the container #scroll and add that back to the position() arg.
var $scroll = $('#scroll');
$('p').click(function(e){
var $this = $(this);
$scroll.animate({
"scrollTop": $this.position().top + $scroll.scrollTop()
}, 1000);
});
http://jsfiddle.net/yCEap/1/
To just get the value:
var value = $('#scroll').scrollTop();

Add new item to bottom of scrollabe div

I'm trying to append a div to the bottom of a another div, by clicking a button in javascript, but once the height of the outer container is reached, it no longer scrolls the list to the bottom, after an insert.
Please see the fiddle here
If you click the red add button until you get to about 13 items in the list, it seems something goes wrong with the scrollTop function, and it it no longer functions correctly (hovers around the same spot in).
I'm pretty lost on this, and have tried a bunch of different combinations of css settings for both the container and side div. Please help me.
I've reformatted your code to be more jQuery-esque. The main change, however, was to change the list.scrollTop() function so that it just scrolls to the bottom of list:
$(document).ready(function() {
var list = $("#q-d-list");
$(document).on('click', '#add', function() {
$('.active', list).removeClass("active");
var count = list.children().length + 1;
var active = $('<div />', {
'data-qid': count,
'class': 'mli active'
}).text('q' + count).appendTo(list);
list.scrollTop(list[0].scrollHeight);
});
});​
Demo: http://jsfiddle.net/MrvcB/19/
Use
list.scrollTop(list.get(0).scrollHeight);
rather than
list.scrollTop($(".active").offset().top);
Try:
$(document).ready(function () {
var count = 2;
$("#add").live("click", function () {
var list= $("#q-d-list");
// remove the active class from the old item
var $clone = $(list.find("div:last-child").removeClass("active").clone());
count+=1;
var str_count = "q"+count.toString();
$clone.addClass("active").attr("data-qid",str_count).text(str_count);
list.append($clone);
list.scrollTop(list.get(0).scrollHeight);
});
});
http://jsfiddle.net/H4Kb3/

Categories

Resources