make div do -200px multiple times? - javascript

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');

Related

Toggle style same as class in pure javascript

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";
}
});

How Can I set variable width with !importanat using JavaScript/jQuery

Ia have a div named "#idDayNrCell". I want to get its width then do some calculations and apply it to another div called ".event". I am using bootstrap so i need to apply !important aswell. I am new to javascript/jquery.
I tried something like this. But it didn't wotk
$(document).ready(function(){
var cellWDTstr = ($("#idDayNrCell").css("width")); //get width
var cellWDT = cellWDTstr.substr(0,cellWDTstr.length-2); //remove the "px" part
console.log(cellWDT);
var GunSayisi=2; //how long is the event (2 for example)
// after tihs things get complicated for me
// if the even is minimum 2 days i need a different width. calculated below
var wdtEnAz2 = ((cellWDT-30)*GunSayisi + 30*(GunSayisi-1)).toString();
console.log(wdtEnAz2);
var setWdt = GunSayisi>1 ? wdtEnAz2 : calWdt;
//after here it is expoerimental code which I am failed
console.log(setWdt);
setWdt+= 'px';
console.log(setWdt);
$(".event").style.setPsetProperty('width',setWdt,'important');
});
this is the html
Using ES6,
var width = "100px";
$(".event").attr('style', `width: ${width} !important`);
Add like this :
$('.event').attr('style', 'width: '+ setWdt +' !important');
You can use css property from jquery, please find below code snippet :
$(".event").css( "width", function(
setWtd ) {
return setWtd + '!Important';
});

change class of div on scroll HTML5 with data attribute

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.

How to find the height of the var that has html content in it

function appData (arg) {
var tmp ='<div class="eventPopUp" z-index:6;">asdfasd <br> asdfasd <br> asdfasd <br> asdfasd<div style="clear:"></div></div>'
$(arg).html(tmp);
var off= $(tmp).offset().left;
var wid = $(tmp).width();
//var hei = $(arg).children().height();
var hei = $(tmp).outerHeight();
console.log('width is ' + wid + ' height is ' + hei);
}
Hi in above function i am making a variable that has html elements in it and i want to know the height and width of the tmp variable(becasue the content gets updated dynamically) My problem is i can get the width of the variable tmp by using width() method and i am getting height 0 by using height() method. please help me to find the height of the var tmp. and if i explictly give height by using style then height() method is giving proper answer and arg is 'li' were i append this varible.
jQuery seems to be confused as to exactly which element you are selecting when doing $(tmp) and therefore returns an empty height.
If you define the string as an object explicitly on initialisation, the height can be calculated once it's attached to the DOM. Try this:
function appData(arg) {
var $tmp = $('<div class="eventPopUp">asdfasd <br> asdfasd <br> asdfasd <br> asdfasd<div style="clear:"></div></div>')
$(arg).append($tmp);
var off = $tmp.offset().left;
var wid = $tmp.width();
var hei = $tmp.outerHeight();
console.log('width is ' + wid + ' height is ' + hei);
}
Example fiddle
The reason why you are getting 0, is most likely because you are reading the height before the element has any content in it. In other words, try using document ready
$( document ).ready(function() {
// call appData function here
});
If this doesn't work, try using setTimeout
x = setTimeout(function() {
// call appData or read height and if height of my selection is != 0 then
// {
// clearTimeout(x);
// myHeight = height of my selection
// call function that does something with it and send it as a param
// }
}, 1000);
You check for the height every second until the height is different from 0. This is a hack, I don't recommend it, unless you start leaving forehead marks on the wall.

jquery reconstructing a selector from a string

I am taking the value of a select element and trying to modify it so that I can have access to the onscreen preview element that the select item represents. Here is the first part of the code...
$("#single_area_select").change(function(){
var $element = '#preview_' + $("#single_area_select").val().toLowerCase();
elementChangedOrSelected($element);
});
And the critical part of the elementChangedOrSelected() method...
function elementChangedOrSelected(element){
element = '$("' + element + '")';
alert(element);
var position = element.position();
alert(position);
My first alert makes it look like i've got it right (ie, $("#preview_title") ), but the second alert doesn't make an appearance which tells me that the position query is failing. Can anyone see something that I can't?
function elementChangedOrSelected(element){
element = $(element);
alert(element);
var position = element.position();
alert("left: " + position.left + ", top: " + position.top);
}
you just need to do this:
position = $(element).position();

Categories