I've got some code where when a button is clicked it toggles an active class. At the same time I need to set a top-margin on the toggled element, which also needs to be removed once the button is clicked again and the toggled class is removed. I can't set the top-margin as part of the active class as I need to get the value of the margin dynamically by checking the height of another element.
This is the code I've got to toggle the class and add the margin
var sizeBtn = document.querySelector(".size-toggle-btn");
var sizeItems = document.querySelector(".select-items");
var elementHeight = document.querySelector(".Detail-Container__inline").offsetHeight ;
sizeBtn.addEventListener("click", function(e) {
sizeItems.classList.toggle('size-toggle--active')
sizeItems.style.marginTop = "-" + elementHeight + "px";
});
However, obviously this doesn't remove the style when the button is clicked again so basically I need to toggle the style just like the active class. Is there anyway to do this?
You need to check if className is there or not so the code could be:
var sizeBtn = document.querySelector(".size-toggle-btn");
var sizeItems = document.querySelector(".select-items");
var elementHeight = document.querySelector(".Detail-Container__inline").offsetHeight ;
sizeBtn.addEventListener("click", function(e) {
if(sizeItems.classList.contains('size-toggle--active')) {
sizeItems.classList.remove('size-toggle--active')
sizeItems.style.marginTop = null;
}
else{
sizeItems.classList.add('size-toggle--active')
sizeItems.style.marginTop = "-" + elementHeight + "px";
}
});
Related
Hi I'm trying to add class to the selectedlList item & also add class if I scroll to the specific div. for example of scroll on div#six number six(6) in the menu should also have class active.
[see my code and demo here][1]
[1]: https://codepen.io/GoPerov/pen/aZmVgE
Try this code, Here's your updated pen
$(document).ready(function(){
$(".page-scroll").click(function(){
$(".page-scroll").removeClass("active"); //removes current active class
$(this).addClass("active"); // adds active class to specific click
})
});
Update your code as below.
You need to manually check for which div is currently active with scroll position.
Updated codepen demo
$(document).ready(function() {
$(".page-scroll").click(function() {
$(".page-scroll").removeClass("active"); //removes current active class
$(this).addClass("active"); // adds active class to specific click
});
});
$(window).scroll(function() {
var selectedDiv = $(".page-scroll:first");
var topOffset = 1;
var windowTop = $(window).scrollTop();
$(".page-scroll").each(function() {
var id = $(this).attr("href");
var offset = ($(id).offset() || {
top: 0
}).top - windowTop;
if (offset < 1 && (topOffset == 1 || offset > topOffset)) {
topOffset = offset;
selectedDiv = $(this);
}
});
if (!selectedDiv.hasClass("active")) {
$(".page-scroll").removeClass("active");
selectedDiv.addClass("active");
}
});
I am trying to move a div -200px from his original position when I press a button. Now I want to be able to do this multiple times.
function leftAnimate(){
original = document.getElementById("sliderzelf").setAttribute("style", "margin-left: -200px;");
}
This piece of code ( I assume, correct me if Im wrong.) really sets the attribute ONCE to -200px. Is there any way I can make this do -200px from every new starting position?
Since you have used the jquery-animate tag, I shall presume you have jQuery. In which case the following should work:
function leftAnimate() {
$("#sliderzelf").css("margin-left", "-=200");
}
call this function however you like, add a css transition on the element if you want it to slide or whatever. happy coding!
function leftAnimate(){
var el = document.getElementById("section");
var curMargin = window.getComputedStyle(el)['margin-left'].replace('px', '');
var newPos = Number(curMargin - 200);
original = el.setAttribute("style", "margin-left:" + newPos + "px;");
}
if you element is an absolute element, try use the Left instead margin-left, or
You can try with jQuery:
function leftAnimate(){
var actualPosition = $("#sliderzelf").css("left");
original = document.getElementById("sliderzelf").setAttribute("style", "margin-left: " + (actualPosition - 200).toString() + "px;");
}
Using pure javascript:
function leftAnimate(){
//get the button
var btn = document.getElementById("sliderzelf");
//get the current margin
var currentMargin = btn.style.marginLeft.replace("px", "");
//calculate the new margin
var newMargin = currentMargin - 200;
//check if the new margin is valid (optional)
if (newMargin >= 0)
btn.setAttribute("style", "margin-left: " + newMargin + "px;") //set the new margin
}
<button id="sliderzelf" style="margin-left: 600px" onclick="leftAnimate()">
Click me!
</button>
With jquery just change the function to:
$("#sliderzelf").css('margin-left', '-= 200');
What I am trying to do is to call a function every time a person scrolls that checks the current class of container and adds +1 to the current value of the current data attribute and then toggles the class relative to the data attribute it is currently changing the class on scroll but giving a "NaN. I am already running this function on click and it works fine.
here is a fiddle.
http://jsfiddle.net/kaL63/1/
This is my function on scroll
var timeout;
$(window).scroll(function() {
if(typeof timeout == "number") {
window.clearTimeout(timeout);
delete timeout;
}
timeout = window.setTimeout( check, 100);
});
My html Looks like this
<div class="container year-1987" data-year-index="1987">
Some Content
</div>
the function I am calling right now that I think should work..
function check(){
var
animationHolder = $('.container'),
currentClass = animationHolder.attr("class").match(/year[\w-]*\b/);
var goToYear = $('.container').data('year-index');
var goToYear2 = parseInt(goToYear,1000) + 1;
animationHolder.toggleClass(currentClass + ' year-' + goToYear2);
animationHolder.attr('data-year-index', goToYear2);
}
My working code on click
$("a").click(function (e) {
e.preventDefault();
var
animationHolder = $('.container'),
currentClass = animationHolder.attr("class").match(/year[\w-]*\b/);
var goToYear = $(this).data('year-index');
animationHolder.toggleClass(currentClass + ' year-' + goToYear);
animationHolder.attr('data-year-index', goToYear);
I rewrote your check method:
function check() {
var $container = $('.container'),
currentYear = $container.data('m-index'),
nextYear = 1 + currentYear;
$container.removeClass('m-' + currentYear).addClass('m-' + nextYear);
$container.data('m-index', nextYear);
}
I made the following changes:
There is no need for the regular expression since we can generate the class name ourselves.
I am not sure why you were originally using two separate data-attributes (m-index and year-index), but I switched them to both match. If you need both of them, some more logic is needed to use year-index after the initial call.
I am now updating m-index via .data() rather than setting a data attribute.
This method seemed to work fine for me.
I'm dynamically generating a div using JavaScript. When mouse is over certain elements in the page the new div appears. On mouseout it disappears. All that is working fine. But I want the div to be top-positioned according to the element the mouse was over of. So I record the position of the element with getBoundingClientReach:
function lopen(AbstId) { //called OnMouseOver
var rect = document.getElementById(AbstId).getBoundingClientRect();
var st3="px";
divtop = rect.top+st3 ;
alert ("Hello :" + divtop); //for checking purposes only
if (this.element == null) {
this.element = document.createElement('div');
this.element.id = "myPopup";
this.element.className = "myPopupBody";
this.element.onmouseover = 'prevent()'; //if mouse over new div, do not close
this.element.style["top"] = divtop; //HERE IS MY PROBLEM
}
document.body.appendChild(this.element);
popUpDetails();
}
function lclose () { //called OnMouseOut
document.getElementById("myPopup").innerHTML = " ";
document.body.removeChild(this.element);
}
The piece of code
this.element.style["top"] = divtop;
is getting the correct top value on first event, but do not actualize for further onmouseover events, even though divtop is actually refreshing (I check with the alert of 5th line).
Does anyone spot the problem?
Again, just for completeness. The problem was an incorrect assignment of style: top. Below the right code
function lopen(AbstId) { //called OnMouseOver
var rect = document.getElementById(AbstId).getBoundingClientRect();
var st3="px";
divtop = rect.top+st3 ;
//alert ("Hello :" + divtop); //for checking purposes only
if (this.element == null) {
this.element = document.createElement('div');
this.element.id = "myPopup";
this.element.className = "myPopupBody";
this.element.onmouseover = 'prevent()'; //if mouse over new div, do not close
//this.element.style["top"] = divtop; //here WAS my problem -deleted line
}
document.body.appendChild(this.element);
document.getElementById("myPopup").style["top"] = divtop; //here right code
popUpDetails();
}
I'm trying to create a button that resizes down images inside it's div,
function aumenta(){
var mydiv = $('div[name|="visualizacoes"]');
var curr_width = parseInt(mydiv.style.width);
var curr_height = parseInt(mydiv.style.height);
if (curr_width < 4123) {
mydiv.style.width = (curr_width + 412) +"px";
mydiv.style.height = (curr_height + 466) +"px";
}
}
it's not working, maybe this is not the way to get the element's name?
My problem is that i have several div's hidden that show up on menu click,
I'm trying to get all of them to resize even if they're hidden, that's why im targeting it's name, could be the class as well!! Please help! Thanks
Create a class, then make all the images a member of that class.
If you do this, you can then use the jQuery "each()" method to iterate through each element, and manipulate them in a loop...
$('.<classname>').each(function(e){
var element = $(this);
var currWidth = element.width();
var currHeight = element.height();
if( currWidth < 4123 ){
element.width( currWidth + 412 );
element.height( currHeight + 412 );
}
});
In the above I've also used the jQuery width() and height() methods to get and set the elements height and width.