Adding / removing classes when scrolling on multiple elements - javascript

I was using a script (that I probably found here) to add / remove classes on elements while scrolling. The scripts associates href from a menu to add / remove classes to corresponding element in the page. The script works fine when using one menu and one set of elements, but I tried to make it usable with multiple menus and I can't seem to find what's wrong. I get an error with the getTargetTop() function, but I can't resolve it.
Here is the code I'm using :
$(window).scroll(function(e){
checkSectionSelected($(window).scrollTop());
});
function getTargetTop(elem){
console.log(elem.attr('href'));
var id = elem.attr("href");
var offset = 0;
return $(id).offset().top - offset;
}
var sections = $('ul.ctrl a');
var mainmenu = $('nav a');
function checkSectionSelected(scrolledTo){
var threshold = 100;
var i;
for (i = 0; i < sections.length; i++) {
var section = $(sections[i]);
var target = getTargetTop(section);
if (scrolledTo > target - threshold && scrolledTo < target + threshold) {
$('.char').removeClass('active');
$('.char'+section.attr('href')).addClass('active');
sections.parent('li').siblings('li').removeClass("active");
section.parent('li').addClass("active");
}
};
var m;
for (m = 0; m < mainmenu.length; m++) {
var link = $(mainmenu[m]);
var newTar = getTargetTop(link);
if (scrolledTo > newTar - threshold && scrolledTo < newTar + threshold) {
sections.parent('li').siblings('li').removeClass("active");
section.parent('li').addClass("active");
}
};
}
Thanks for helping!

Related

getElementByTagName(a) for autoscroll

What I have now is:
var a = document.getElementsByTagName('a');
I use this to get all elements with an 'a' and when I scroll it autoscrolls to the next 'a' element.
The problem with that is that I also use links (that use an a href="") so sometimes it scrolls to a link instead of an <a name="name"></a>. Is their anyway to fix this? Like:
var a = document.getElementsByTagName('a name=""');
(this one doesnt work)
If full code is needed I will add it below, but its probably not needed.
(function () {
var delay = false;
$(document).on('mousewheel DOMMouseScroll', function (event) {
event.preventDefault();
if (delay) return;
delay = true;
setTimeout(function () {
delay = false
}, 800);
var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;
var a = document.getElementsByTagName('a');
if (wd < 0) {
for (var i = 0; i < a.length; i++) {
var t = a[i].getClientRects()[0].top;
if (t >= window.innerHeight * 0.95) break;
}
}
else {
for (var i = a.length - 1; i >= 0; i--) {
var t = a[i].getClientRects()[0].top;
if (t < -window.innerHeight * 0.5) break;
}
}
$('html,body').animate({
scrollTop: a[i].offsetTop
}, 800);
});
})();
You can use QuerySelector for HTML 5 supporting browsers .You can check its support from http://caniuse.com/#feat=queryselector
QuerySelectorAll
document.querySelectorAll("a[name='<setname>']");
For older browsers use Jquery
$("a[name='<setname>']")
If you don't want to set a specific name just leave it blank. The selector is same for both JQuery and HTML 5 querySelector
document.querySelectorAll("a[name]");
or
$("a[name]")
Try with querySelectorAll()
document.querySelectorAll("a[name='examplename']");
find a empty
document.querySelectorAll("a[name='']");

Disable hover when key pressed

I implement a custom dropdown, and I have a problem when I move by keyboard: hover works too and I don't know how to disable it. I've paste my code here http://jsfiddle.net/4o0bcv1d/, but here my code works correct. When I copy code to index.html - hover works again, when I move by keyboard.
How I can fix it?
var doc = document;
var keydown_count = -1;
var dropdown_content = doc.querySelector('.dropdown-content');
var dropdown_items = doc.querySelectorAll('.dropdown-item');
var dropdown_items_length = dropdown_items.length;
var clear_navigation_hover = function () {
for (var i = 0; i < dropdown_items_length; ++i) {
dropdown_items[i].classList.remove('dropdown-item--hover');
};
}
var navigation_hover_by_keydown = function (event) {
var event = event || event.window;
var UP = 38;
var DOWN = 40;
var SCROLL_STEP = 66;
if (event.keyCode === UP) {
keydown_count--;
if (keydown_count < 0) {
keydown_count = dropdown_items_length - 1;
dropdown_content.scrollTop = 66 * dropdown_items_length;
}
if (keydown_count < (dropdown_items_length - 3)) {
dropdown_content.scrollTop -= 66;
};
} else if (event.keyCode === DOWN) {
keydown_count++;
if (keydown_count >= dropdown_items_length) {
keydown_count = 0;
dropdown_content.scrollTop = 0;
}
if (keydown_count > 3) {
dropdown_content.scrollTop += 66;
};
}
clear_navigation_hover();
dropdown_items[keydown_count].classList.add('dropdown-item--hover');
}
var dropdown_input = doc.querySelector('.dropdown-input');
dropdown_input.addEventListener('keydown', navigation_hover_by_keydown, false);
var navigation_hover_by_hover = function () {
clear_navigation_hover();
this.classList.add('dropdown-item--hover');
keydown_count = this.getAttribute('data-index');
console.log('hover');
}
for (var i = 0; i < dropdown_items_length; ++i) {
dropdown_items[i].addEventListener('mouseover', navigation_hover_by_hover, false);
}
You can use the CSS pointer-events feature to disable hovering on any of the page element. On keypress you need to add this attribute to the body tag like this
document.body.style.pointerEvents = 'none';
and again on key release you could remove this property so that mouse over starts working again. So at key release you need to do
document.body.style.pointerEvents = 'auto';
The pointer-events property allows to exclude an HTML element from being a mouse target. All the descendant elements are also excluded from being a mouse target unless the pointer-events property has been explicitly overridden for that node.
you can set the css selector, instead :hover, anything like :hover:not(.unhover), the class .unhover can be added using js

I'm trying to make a div width expand once clicking on another div

Im trying to make a div expanded once you click on another div. In my case I'm try to make div with some text in it expand when the image is clicked. A link to my JSFiddle - https://jsfiddle.net/txoyuvqn/3/
My javascript that I am using looks like.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '500px'
whattochange[i].style.transition = 'all 1s'
whattochange[i].style.backgroundColor = 'red'
}
}, false);
However when I click on the class called image it effects all the Text classes, i know it's because were changing the css to all of the text divs, however is there a way to make it only effect the correlating div? Or am I going about creating this in the wrong way?
getElementsByClassName returns an array, not a single element.
divs is an array, and you are correctly using a for loop and the index indicator [i] after your variable name divs.
You need a similar for loop for whattochange.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
There may be a better way, but you could do it like this:
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
{
divs[i].addEventListener("click", function()
{
var w = document.getElementById(this.id.replace('img', 'text'));
w.style.width = '800px'
w.style.transition = 'all 1s'
w.style.backgroundColor = 'red'
});
whattochange[i].id = 'text' + i;
divs[i].id = 'img' + i;
}
See the fiddle
Javascript
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
}
You have to be sure that the elements exist if your JavaScript code depends on them. The reason why your fiddle didnt work was because, you was not loading the script after the body has finished loading.
In your code, One way of achieving this is by putting the <script> tag at the end of the body like this:
<html>
<head></head>
<body>
<script type="text/javascript">
// code here
</script>
</body>
You can also put all your code in a function for the window.onload event or use jQuery.

How do I set the interval in a for loop?

I'm trying to create a menu of social media icons that slides into and out of the page. The following code works, but it is too fast. It doesn't look like sliding. I think I could adjust the timing using the setInterval() method, but I can't get it to work. This is the code so far:
var socialMedia = document.getElementById("socialmedia");
var stalkMe = document.getElementById("pleasestalkme");
function SM() {
socialMedia.style.position = "fixed";
socialMedia.style.right = "-330px";
}
SM();
stalkMe.addEventListener("click", function(){
if (socialMedia.style.right === "-330px") {
for (i = -330; i <= -30; i++) {
var j = i +"px";
socialMedia.style.right = j;
}
} else if (socialMedia.style.right === "-30px"){
for (i = -30; i >= -330; i--){
var j = i +"px";
socialMedia.style.right = j;
}
}
}, false);
You should have a look at CSS transitions. Basically you just need to change the right style from 300px to 0px and using transition: right 1s; you would see your element being animated
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions
Otherwise, you could have a look at jQuery.... (I feel bad).
Prior to the solution, a word of warning: you actually should not use this code snippet. Instead heed the advice of floribon and look into css transitions.
However, if you absolutely must do it the outmoded way:
for (i = -330; i <= -30; i++) {
var j = i +"px";
socialMedia.style.right = j;
}
write
var hnd;
i = -330;
hnd = setInterval ( function () {
var j = i +"px";
socialMedia.style.right = j;
i++;
if (i > -30) {
clearInterval(hnd); // end activity
}
}, 50 ); // interval length in ms

Slide dynamically added content with jQuery

I'm trying to create a simple content slider that could handle dynamically added content to the slider. None of the "lightweight" plugins I found provided such functionality or, if it did, it didn't work correctly.
var $left = $('.left'),
$right = $('.right'),
$months = $('.sub ul');
$left.click(function(){
for(i = 0; i < 3; i++){
$months.find('li').first().before($.parseHTML('<li>xxx</li>'));
}
pos = $months.position();
$months.css('left', pos.left + 90);
});
$right.click(function(){
for(i = 0; i < 3; i++){
$months.find('li').last().after($.parseHTML('<li>xxx</li>'));
}
pos = $months.position();
$months.css('left', pos.left - 90);
});
This is the code I've got so far and here's a fiddle with an example - http://jsfiddle.net/kkr4zg0r/2/. It kind of works, but the problem is that since new content is added the navigation goes off (you can see what I mean by clicking left-right a couple of times).
I understand what's the problem for this - the newly added items "shift" the content and I need to do better calculations than substracting/adding 90px to the left position of the element but I can't figure out how to get the correct index of the elements and basically get this sliding by exactly (and correctly) by 3(or 6) elements at the time.
Currently the code is adding extra elements whenever a navigation button is pressed, if I could get the index of the currently visible first/last element, I could probably tell whether I need to add more elements and only add them then.
This is a basic illustration of what I'm trying to achieve
edit
I've changed the jsfiddle to the correct one.
The whole idea is to check when adding elements is necessary and when shift is enough:
Fiddle
$(document).ready(function()
{
var $main = $('.main'),
$left = $('.left'),
$right = $('.right'),
$months = $('.sub ul');
var addCount = 3;
var liWidth = 30;
var shiftX = addCount * liWidth;
$left.click(function()
{
var currentLeft = parseInt($months.css('left'));
var totalLength = $months.find('li').length * liWidth;
if (-currentLeft + $main.width() >= totalLength)
{
for (var i = 0; i < addCount; i++)
{
$months.find('li:last').after('<li>xxx</li>');
}
}
$months.css('left', currentLeft -= shiftX);
});
$right.click(function()
{
var currentLeft = parseInt($months.css('left'));
if (currentLeft < 0)
{
$months.css('left', currentLeft += shiftX);
}
else
{
for (var i = 0; i < addCount; i++)
{
$months.find('li:first').before('<li>xxx</li>');
}
}
});
});

Categories