How can I increase a CSS property's value repeatedly on click? - javascript

I want to add (in this case, decrease, technically) the value of an element each time a different element is clicked. What I have so far:
$("#trigger_heritage").click(function () {
$(".heritage_content ul").css("margin-left", + -880);
// So each time clicking shall move the .heritage_content ul-element 880px further left
});
It gets 880px far left, but only once. What I want is that this value gets increased each time the other element gets clicked.
How would I do that?

You can provide a string in the format -=[value] to the css() method which you can use to amend the current value. Try this:
$("#trigger_heritage").click(function () {
$(".heritage_content ul").css("margin-left", '-=880');
});
Working example

Here is a simple example:
$(document).ready(function() {
var move = 0;
$(".left").click(function () {
move -= 25;
$(".move").css("margin-left", move + "px");
});
$(".right").click(function () {
move += 25;
$(".move").css("margin-left", move + "px");
});
})
Fiddle: https://jsfiddle.net/gjfjahjo/

Set a variable, say $marginLeft, and increment this each time the function is called, then set the margin-left:$marginLeft....

Related

Pure js add and remove (toggle) class after scrolling x amount?

I don't want to use jQuery for this.
It's really simple, I just want to add a class after scrolling past a certain amount of pixels (lets say 10px) and remove it if we ever go back to the top 10 pixels.
My best attempt was:
var scrollpos = window.pageYOffset;
var header = document.getElementById("header");
function add_class_on_scroll() {
header.classList.add("fade-in");
}
function remove_class_on_scroll() {
header.classList.remove("fade-in");
}
window.addEventListener('scroll', function(){
if(scrollpos > 10){
add_class_on_scroll();
}
else {
remove_class_on_scroll();
}
console.log(scrollpos);
});
But console shows a number that continues to grow regardless of scrolling up or down. And the class fade-in never gets added, though console shows we past 10.
You forgot to change the offset value in the scroll handler.
//use window.scrollY
var scrollpos = window.scrollY;
var header = document.getElementById("header");
function add_class_on_scroll() {
header.classList.add("fade-in");
}
function remove_class_on_scroll() {
header.classList.remove("fade-in");
}
window.addEventListener('scroll', function(){
//Here you forgot to update the value
scrollpos = window.scrollY;
if(scrollpos > 10){
add_class_on_scroll();
}
else {
remove_class_on_scroll();
}
console.log(scrollpos);
});
Now you code works properly
Explanation
There is no documentation for that, like you asked for. This is just an issue in the logic workflow.
When you say that scrollpos = window.scrollY your page is at an top-offset of 0, so your variable stores that value.
When the page scrolls, your scroll listener will fires. When yout listener checks for the scrollpos value, the value is still 0, of course.
But if, at every scroll handler, you update the scrollpos value, now you can have a dynamic value.
Another option is you to create a getter, like
var scrollpos = function(){return window.scrollY};
This way you can dynamically check what that method will return for you at every offset.
if(scrollpos() > 10)
See? Hope that helped. (:
One simple way to achieve what you want (one line of code inside the scroll event):
window.addEventListener('scroll', function(e) {
document.getElementById('header').classList[e.pageY > 10 ? 'add' : 'remove']('fade-in');
});
#header {
height: 600px;
}
.fade-in {
background-color: orange;
}
<div id='header'></div>
just use the method toggle in classList
header.classList.toggle('fade-in')

onmouseover-triggered function keeps triggering on mouse over

I have a function, which is triggered when the mouse goes over a div.
The div contains a link, which is 100% height and width of the containing div. The link contains an image, which the function moves when onmouseover the grandparent (the div).
The function moves the image to the right and then back to the middle.
When I move the mouse over the div the function is triggered but moves the image by only 5px (one loop of the function) and keeps moving it 5px when I move the mouse around - the function is not looping and just loops once on every onmouseover.
<div onmouseover="jotArrow(this);" class="latest-entry latest-entry-third" id="news-link-home">
<a class="home-square-link" href="hello.php">Reviews<br/><img src="<?php echo $config['file_path']; ?>/images/squares-arrow.png" width="60px"/></a>
</div>
JS:
var arrowPos = 0;
var Arrow;
function jotArrow(arrow)
{
Arrow = arrow.getElementsByTagName('img')[0];
if (arrowPos < 50) {
arrowPos = arrowPos + 5;
Arrow.style.left = arrowPos + 'px';
setTimeout(jotArrow, 10);
} else {
jotArrowBack(arrow)
}
}
function jotArrowBack(arrow)
{
if (arrowPos > 0) {
arrowPos = arrowPos - 5;
Arrow.style.left = arrowPos + 'px';
setTimeout(jotArrowBack, 10);
}
}
To make sure the code is correct, I modified it a little (from that above) so that it makes an image in a different div move (onmouseover of div1 causes div2 image to move). And it worked fine.
So I am guessing it has something to do with the image being inside the div and the mouse goes over more than one element. But really I don't see why this would be an issue as the function does not care about onmouseout it should just perform it's whole task on the first onmouseover.
I have tried putting the onmouseover attribute on all three elements (the div, the a and the img) separately and all at the same time - same problem.
Your code appears to have two problems. As you mentioned, you get multiple mouseover events which confuse the code, but the other problem is that jotArrow fetches the Arrow element every time, and the second time it can't find it because your setTimeout call doesn't pass the parameter. When you switch the code to move another element I assume you just write something like document.getElementById('blah') which picks up the same element each time.
One approach would be to use a helper function initArrow, something like this:
function initArrow(arrow)
{
if (arrowPos == 0) {
Arrow = arrow.getElementsByTagName('img')[0];
jotArrow();
}
}

FadeIn is not giving proper timing

I have 3 divs I want to show each of them 1 sec apart. But that does not seem to happen . What is actually happening in the loop. Please explain!!Currently all the divs appear together. But i want to show them one at a time.
I want the second DIV to appear after the first div has appeared.
http://jsfiddle.net/wilsonrufus/TUL6s/
var blockOne = $('#block1');
blockInner = blockOne.find('.inner-block');
blockInner.fadeOut();
blockInner.each(function (index, value) {
time = 2000+(index*5000); <- just expermenting
$(this).fadeIn(time);
console.log(time)
});
Try chaining and use a callback function to handle each time the fadeIn of the next element
http://jsfiddle.net/blackjim/TUL6s/1/
var blockOne = $('#block1');
blockInner = blockOne.find('.inner-block');
var fadeNextIn = function(){
if($(this).next()){
$(this).next().fadeIn(1000,fadeNextIn);
}
}
blockInner.fadeOut('slow')
.first().fadeIn(1000,fadeNextIn);
Use delay if its not the first div:
blockInner.each(function (index, value) {
$(this).delay(index > 0 ? 2000*index : 0).fadeIn(2000);
});
http://jsfiddle.net/TUL6s/5/

jquery moving element at the end of the list makes container disapper, seems like prepend

I'm trying to make a very simple rotating banners list.
Fiddle is here: http://jsfiddle.net/a9dAm/
if ($("#ads").length > 0) {
var count_banners = $("#ads a").length;
var delay_time = 1000;
var i = 1;
while (count_banners >= i) {
$("#ads a:nth-child("+ i +")").delay(delay_time * i).show(1, function(){
$(this).fadeOut("slow").prepend($("#ads"));
});
i++;
}
}
Prepend breaks everything and #ads disappears all together, what is going on? or what am I doing wrong?
I think you want .prependTo(), not .prepend().
$(this).fadeOut("slow").prependTo($("#ads"));
or just
$(this).fadeOut("slow").prependTo("#ads");
The .prepend() function prepends its argument to the element from which you call it.
It's disappearing because you were using .prepend rather than .prependTo. Basically, you were moving ads instead of the single ad.
Updated fiddle: http://jsfiddle.net/klatzkaj/a9dAm/1/
This is the relevant line: $(this).fadeOut("slow").prependTo($("#ads"));

Write on html on load

I have created a function who tracks on which slide I am currently on and display the result
e.g. If I am on slide 2 of 3 it will display 2/3
my problem is that right now it is set to do that every time I click the forward arrow but it displays nothing on page load.
$('.forward').click(function() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
$("#bottom-image").html(current + "/" + count) ;
});
I am trying to find out how to execute this function on page load and where to put it in my code. I am currently learning Javascript through Codecadamedy so I have a basic knowledge of Javascript but I am not enough fluent right now to figure this one out.
Here is a link to the current non working code : http://www.soleilcom.com/metacor_dev/our-plants.php
It looks like you are using jQuery. To execute a function on DOM load in query, do this:
$(document).ready(function() {
/* your code */
});
In your case, that would be:
$(document).ready(function() {
$('.forward').click(function() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
$("#bottom-image").html(current + "/" + count) ;
});
});
For things like most event handlers, and most other things, initializing at DOM load is good enough. If your code needs to take account for rendered elements or rendered heights, use $(window).load() instead. (In your case DOM load is fine).
Note that this will just establish the click handler at load time. To also run it once, you can do it automatically by either calling the function yourself or triggering a click. To call it yourself, first define another function. The use the function in both the click handler and in one immediate call:
$(document).ready(function() {
var forward = function() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
$("#bottom-image").html(current + "/" + count) ;
}
$('.forward').click(forward);
forward();
});
Or to trigger it yourself, just define the click handler and trigger a click programatically:
$(document).ready(function() {
$('.forward').click(function() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
$("#bottom-image").html(current + "/" + count) ;
}).click();
});
It looks like you are using jQuery, so you would use this:
$(document).ready(function(){
// Code here
});
Or, you can use the shortcut:
$(function(){
// Code here
});
Read more about this on the jQuery website
If you give the function a name, then you can use it multiple times:
$(document).ready(function() {
// Bind to click event
$('.forward').click(forwardSlide)
// Execute function on page load
forwardSlide();
});
function forwardSlide() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
};
Is this what you're looking for?

Categories