How to get JS tab selector to not scroll - javascript

I'm using this JS for tabs. However, it continually makes the selected tab box scroll to the top of the page when clicked.
I can't figure out what part of it is doing that and am trying to get rid of it. Essentially I just want it to function as a normal tab clicker without causing the entire page to scroll.
Any help?
I added a snippet with a large top margin so you can see what happens when you click the tab. I just want those boxes to change without the page physically scrolling to them on its own.
'use strict';
function Tabs() {
var bindAll = function() {
var menuElements = document.querySelectorAll('[data-tab]');
for (var i = 0; i < menuElements.length; i++) {
menuElements[i].addEventListener('click', change, false);
}
}
var clear = function() {
var menuElements = document.querySelectorAll('[data-tab]');
for (var i = 0; i < menuElements.length; i++) {
menuElements[i].classList.remove('active');
var id = menuElements[i].getAttribute('data-tab');
document.getElementById(id).classList.remove('active');
}
}
var change = function(e) {
clear();
e.target.classList.add('active');
var id = e.currentTarget.getAttribute('data-tab');
document.getElementById(id).classList.add('active');
}
bindAll();
}
var connectTabs = new Tabs();
.b-box {margin-top: 1500px;}
.b-tab {
padding: 20px;
border: 1px solid #000;
display: none
}
.b-tab.active {
display: block;
}
.b-nav-tab {
display: inline-block;
padding: 20px;
}
.b-nav-tab.active {
color: #ff4200;
}
<a href="#orange" data-tab="orange" class="b-nav-tab active">
Orange
</a>
<a href="#green" data-tab="green" class="b-nav-tab">
Green
</a>
<a href="#blue" data-tab="blue" class="b-nav-tab">
Blue
</a>
<div class="b-box">
<div id="orange" class="b-tab active">
Orange tab content
</div>
<div id="green" class="b-tab">
Green tab content
</div>
<div id="blue" class="b-tab">
Blue tab content
</div></div>

I updated your code.
Actually you was showing # sign in href so it redirect the position to that box. I removed it.
Good Luck.
'use strict';
function Tabs() {
var bindAll = function() {
var menuElements = document.querySelectorAll('[data-tab]');
for (var i = 0; i < menuElements.length; i++) {
menuElements[i].addEventListener('click', change, false);
}
}
var clear = function() {
var menuElements = document.querySelectorAll('[data-tab]');
for (var i = 0; i < menuElements.length; i++) {
menuElements[i].classList.remove('active');
var id = menuElements[i].getAttribute('data-tab');
document.getElementById(id).classList.remove('active');
}
}
var change = function(e) {
clear();
e.target.classList.add('active');
var id = e.currentTarget.getAttribute('data-tab');
document.getElementById(id).classList.add('active');
}
bindAll();
}
var connectTabs = new Tabs();
.b-tab {
padding: 20px;
border: 1px solid #000;
display: none;
}
.b-tab.active {
display: block;
}
.b-nav-tab {
display: inline-block;
padding: 20px;
}
.b-nav-tab.active {
color: #ff4200;
}
<a href="javascript:void(0)" data-tab="orange" class="b-nav-tab active">
Orange
</a>
<a href="javascript:void(0)" data-tab="green" class="b-nav-tab">
Green
</a>
<a href="javascript:void(0)" data-tab="blue" class="b-nav-tab">
Blue
</a>
<div id="orange" class="b-tab active">
Orange tab content
</div>
<div id="green" class="b-tab">
Green tab content
</div>
<div id="blue" class="b-tab">
Blue tab content
</div>

One way would be to add this e.preventDefault(); to your change function and the other way would be to replace href="#orange" with href="javascript:void(0)". All the same with other hrefs.

Related

jQuery - element crossing another element

I have a fixed div on the page which contains a logo and as the user scrolls and this logo passes over other divs I wnat to the change the colour of the logo.
I have this working over a single div but need to it work across multiple so any help appreciated.
The WIP site can be seen here... dd.mintfresh.co.uk - if you scroll down you'll (hopefully) see the logo change from black to white as it crosses an illustrated egg. I need the same to happen when it crosses other divs further down the page.
The script so far...
jQuery(window).scroll(function(){
var fixed = jQuery("logo");
var fixed_position = jQuery("#logo").offset().top;
var fixed_height = jQuery("#logo").height();
var toCross_position = jQuery("#egg").offset().top;
var toCross_height = jQuery("#egg").height();
if (fixed_position + fixed_height < toCross_position) {
jQuery("#logo img").css({filter : "invert(100%)"});
} else if (fixed_position > toCross_position + toCross_height) {
jQuery("#logo img").css({filter : "invert(100%)"});
} else {
jQuery("#logo img").css({filter : "invert(0%)"});
}
}
);
Any help appreciated. Thanks!
you need to fire a div scroll event. you can assign
$("div1").scroll(function(){
//change the color of the div1
}
});
$("div2").scroll(function(){
//change the color of the div2
}
});
or you can assign a class to divs which you want to change the color
$(".div").scroll(function(){
//change the color of the div which you are scrolling now
}
});
You can use like this :-
$(window).scroll(function() {
var that = $(this);
$('.section').each(function() {
var s = $(this);
if (that.scrollTop() >= s.position().top) {
if(s.hasClass('active')) {
$('.logo').addClass('invert');
} else {
$('.logo').removeClass('invert');
}
}
});
});
body {
padding: 0;
margin: 0;
}
div {
background: #f00;
height: 400px;
}
.logo {
position: fixed;
top: 0;
left: 0;
width: 100px;
}
.logo.invert {
filter: invert(100%);
}
div:nth-child(even) {
background: #ff0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://dd.mintfresh.co.uk/wp-content/uploads/2018/06/DD_logo.svg" class="logo" />
<div id="page1" class="section"></div>
<div id="page2" class="section active"></div>
<div id="page3" class="section"></div>
<div id="page4" class="section active"></div>
<div id="page5" class="section"></div>
As your site code you can do like this :
$(window).scroll(function() {
var that = $(this);
$('#content > section').each(function() {
var s = $(this);
if (that.scrollTop() >= s.position().top) {
if(s.hasClass('black')) {
$('#logo img').css({filter: 'invert(0%)'});
} else {
$('#logo img').css({filter: 'invert(100%)'});
}
}
});
});

Why does one calculation for my onClick get applied to all elements that I'm looping through

Currently doing some exercise for CSS/Javascript animation. I'm attempting to make a Carousel slider from scratch.. I have 4 divs with 550px in width nested in a wrapper of 2200px, which is then nested in a 550px wrapper with overflow hidden.
I then created 4 LI's that I want to make clickable so that it'll translate the wrapper -550*I degrees for every LI.
I performed a queryselectorall to get all the li's, looped through it with a for loop, and created a function that should apply onclick functionality for each LI button.
The issue that I'm running into is that the first calculation of this transform property is applied to all LI's (the 550 * i for [1] [2] and [3] aren't applied).
Here's the HTML that I'm currently using.
<div id="container">
<div id="wrapper">
<div id="itemOne" >
</div>
<div id="itemTwo">
</div>
<div id="itemThree">
</div>
<div id="itemFour">
</div>
</div>
</div>
<ul>
<li class="button"></li>
<li class="button"></li>
<li class="button"></li>
<li class="button"></li>
</ul>
The Javascript
var wrapper = document.querySelector("#wrapper");
var buttons = document.querySelectorAll(".button");
for(var i = 0; i < buttons.length; i++){
var curBut = buttons[i];
curBut.addEventListener("click", function(){
wrapper.style[transformProperty] = 'translate3d(-'+((0-i) * 550) +'px,0,0'
})
console.log(((0-i) * 550));
}
console.log(buttons);
var transforms = ["transform",
"msTransform",
"webkitTransform",
"mozTransform",
"oTransform"];
var transformProperty = getSupportedPropertyName(transforms);
function getSupportedPropertyName(properties) {
for (var i = 0; i < properties.length; i++){
if(typeof document.body.style[properties[i]] != "undefined") {
return properties[i];
}
}
return null;
}
If anyone could explain why the function isn't applying the different changes for the wrapper for each LI, that'd be great! Thanks!!
The global variable i is not copied into each listener, it's shared between the listeners. When you click a button, i is already set to its final value which is 4. As a possible workaround you could override the global variable with a local variable, and get the index on click using indexOf :
var wrapper = document.querySelector("#wrapper");
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
var curBut = buttons[i];
curBut.addEventListener("click", function() {
var i = Array.prototype.indexOf.call(buttons, this);
wrapper.style[transformProperty] = 'translate3d(-' + (i * 260) + 'px,0,0)';
});
}
var transforms = ["transform",
"msTransform",
"webkitTransform",
"mozTransform",
"oTransform"];
var transformProperty = getSupportedPropertyName(transforms);
function getSupportedPropertyName(properties) {
for (var i = 0; i < properties.length; i++) {
if (typeof document.body.style[properties[i]] != "undefined") {
return properties[i];
}
}
return null;
}
#container {
overflow: hidden;
background: gray;
margin-bottom: 1em;
width: 260px;
height: 100px;
}
#wrapper {
width: calc(4 * 260px);
height: 100px;
}
#wrapper div {
padding: 0 1em;
width: calc(260px - 2em);
line-height: 100px;
height: 100px;
float: left;
color: white;
font-size: 3em;
font-weight: bold;
text-align: center;
}
<div id="container">
<div id="wrapper">
<div id="itemOne">1</div>
<div id="itemTwo">2</div>
<div id="itemThree">3</div>
<div id="itemFour">4</div>
</div>
</div>
<div>
<button type="button">button 1</button>
<button type="button">button 2</button>
<button type="button">button 3</button>
<button type="button">button 4</button>
</div>

how to change text color and back ground color of span when ng click function occur

I have two button. Today and tomorrow. And i have ng click function for both button. What i need is by default my button back ground color will be white. and text color will be red.
When i click my totday button , i need my back ground color to chnage to blue, and text color have to chnage to white.
and if i press tomorrow button this same design have to apply for this button. and my today button have to be default color. How to do this :
here my code :
<div class="row" style="height: 52px;">
<div class="col col-50" style="border-right: 1px #ccc solid; padding-top: 17px; text-align: center;" ng-click="GetDetails()" id="1">
<span class="assertive" style="margin: 0px;color: #B90143;">TODAY</span>
</div>
<div class="col col-50" style="padding-top: 17px;text-align: center;" ng-click="GetTomorrowDetails()">
<span class="assertive" style="margin: 0px;color: #B90143; width: 100%;">TOMORROW</span>
</div>
</div>
My controller for ng-cilck for both button :
$scope.GetDetails = function(){
$ionicLoading.hide();
$scope.orders.length = 0
MydeliveryFactory.save($scope.orderInfo, function(response){
var AllOrderValues = response.allorders;
for (var i = AllOrderValues.length - 1; i >= 0; i--) {
if(AllOrderValues[i].dateAdded == todaydate && AllOrderValues[i].monthAdded == todayMonth ) {
$scope.orders.push(AllOrderValues[i]);
$ionicLoading.hide();
console.log($scope.orders);
}
}
$window.localStorage.setItem("MyDeliverYOrders", JSON.stringify($scope.orders));
});
}
$scope.GetTomorrowDetails = function(){
$ionicLoading.show();
$scope.orders.length = 0
MydeliveryFactory.save($scope.orderInfo, function(response){
var Allvalues = response.allorders;
for (var i = Allvalues.length - 1; i >= 0; i--) {
if(Allvalues[i].dateAdded == tomorrowdate && Allvalues[i].monthAdded == tomorrowMonth) {
$scope.orders.push(Allvalues[i]);
$ionicLoading.hide();
console.log($scope.orders);
}
}
$window.localStorage.setItem("MyDeliverYOrders", JSON.stringify($scope.orders));
});
}
You can toggle classes with ng-class and $scopes.
I have added ng-class="{'active':active.today}" in button, it means active class will be added when active.today is true and will remove when active.today is false, same for tomorrow button,
and in js function is just toggling $scope between true and false.
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.active = {};
$scope.GetDetails = function() {
$scope.active.tomorrow = false;
$scope.active.today = true;
}
$scope.GetTomorrowDetails = function() {
$scope.active.today = false;
$scope.active.tomorrow = true;
}
});
.active {
background: blue;
color: #fff!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl" class="row" style="height: 52px;">
<div class="col col-50" style="border-right: 1px #ccc solid; padding-top: 17px; text-align: center;" ng-click="GetDetails()" id="1">
<span class="assertive" ng-class="{'active':active.today}" style="margin: 0px;color: #B90143;">TODAY</span>
</div>
<div class="col col-50" style="padding-top: 17px;text-align: center;" ng-click="GetTomorrowDetails()">
<span class="assertive" ng-class="{'active':active.tomorrow}" style="margin: 0px;color: #B90143; width: 100%;">TOMORROW</span>
</div>
</div>
Have a look at ngClass, using this you will be able to dynamically change the class assigned to your buttons.
Your button html could look a little like this:
<button ng-class="[btn, btn-primary, {today: active-class}]" ng-click="GetDetails()">Today</button>
<button ng-class="[btn, btn-primary, {!today: active-class}]" ng-click="GetTomorrowDetails()">Tomorrow</button>
You controller, something like this:
$scope.today = true;
$scope.GetDetails = function() {
$scope.today = true;
}
$scope.GetTomorrowDetails = function() {
$scope.today = false;
}
Add a common class to your button and provide them the default css.
<div class="row" style="height: 52px;">
<div class="btn col col-50" style="border-right: 1px #ccc solid; padding-top: 17px; text-align: center;" ng-click="GetDetails($event)" id="1">
<span class="assertive" style="margin: 0px;color: #B90143;">TODAY</span>
</div>
<div class="btn col col-50" style="padding-top: 17px;text-align: center;" ng-click="GetTomorrowDetails($event)">
<span class="assertive" style="margin: 0px;color: #B90143; width: 100%;">TOMORROW</span>
</div>
</div>
.btn {
background-color: white;
color: red;
}
And in your Controller, handle your click handlers:
$scope.GetDetails = function(event) {
$scope.defaultColors();
event.target.style.backgroundColor = "blue";
event.target.style.color = "white";
};
$scope.GetTomorrowDetails = function(event) {
$scope.defaultColors();
event.target.style.backgroundColor = "blue";
event.target.style.color = "white";
};
$scope.defaultColors = function() {
[].slice.call(document.getElementsByClassName("btn")).forEach(function(el, i) {
el.style.backgroundColor = "white";
el.style.color = "red";
});
};

Pure JS // Hide div when another divs class has been changed

Note: I can't use jQuery, only vanilla javascript
I'm not really fluent in pure JS. And this time I can't use any external resources (like jquery).
What I need:
If div1 class is active, hide text2
If div2 class is active, hide text1
I made it somehow to work, but my JS doesn't trigger when the class changes dynamic with another javascript code.
Code that triggers the active class
function activeClass(elem) {
var a = document.getElementsByClassName('item')
for (i = 0; i < a.length; i++) {
a[i].classList.remove('active')
}
elem.classList.add('active');
}
Code that should trigger hide/show when the class changes
if (document.querySelector(".text2").classList.contains("active")) {
document.getElementsByClassName('text1s')[0].style.visibility = 'hidden';
document.getElementsByClassName('text2s')[0].style.visibility = 'visible';
}
if (document.querySelector(".text1").classList.contains("active")) {
document.getElementsByClassName('text2s')[0].style.visibility = 'hidden';
document.getElementsByClassName('text1s')[0].style.visibility = 'visible';
}
What did I do wrong?
Codepen demo
Place your conditions inside click handler.
Add inline visibility style for inactive element
function activeClass(elem) {
var a = document.getElementsByClassName('item')
for (i = 0; i < a.length; i++) {
a[i].classList.remove('active')
}
elem.classList.add('active');
if (document.querySelector(".text2").classList.contains("active")) {
document.getElementsByClassName('text1s')[0].style.visibility = 'hidden';
document.getElementsByClassName('text2s')[0].style.visibility = 'visible';
}
if (document.querySelector(".text1").classList.contains("active")) {
document.getElementsByClassName('text2s')[0].style.visibility = 'hidden';
document.getElementsByClassName('text1s')[0].style.visibility = 'visible';
}
}
body {
margin: 3em;
}
.item {
cursor: pointer;
}
a {
padding: 10px;
}
.active {
color: red;
border: 1px solid red;
}
<a class="item text1" onclick="activeClass(this)">show text</a>
<a class="item text2 active" onclick="activeClass(this)">hide text</a>
<br>
<br>
<h1 class="text1s" style='visibility:hidden;'>TEXT 1</h1>
<h1 class="text2s">TEXT 2</h1>
Updated Codepen

Showing/Hiding Divs with Javascript on click

I'm trying to show/hide tabs on click using just Javascript but I'm getting errors ("Uncaught TypeError: Cannot set property 'className' of undefined tabs.(anonymous function).onclick"). Can someone give me an idea of what the issue might be?
<style>
a { text-decoration: none; }
li { list-style: none; }
li.selected { font-weight: bold; }
.panels div { display: none; }
.panels .selected { display: block; }
</style>
<div id="tabs" class="tabs">
<ul>
<li class="selected">One</li>
<li class="">Two</li>
<li class="">Three</li>
</ul>
</div>
<div id="panels" class="panels">
<div class="selected">This is panel one.</div>
<div class="">This is panel two.</div>
<div class="">This is panel three.</div>
</div>
<script>
var tabs = document.getElementById("tabs").getElementsByTagName("li");
var panels = document.getElementById("panels").getElementsByTagName("div");
for (var i = 0; i < tabs.length; i++) {
new function(i) {
tabs[i].onclick = function() {
tabs[i].className = panels[i].className = "selected";
for (var i = 0; i < panels.length; i++) {
tabs[i].className = panels[i].className = "";
}
}
}(i);
}
</script>
Your inner for loop has an i variable that conflict with the outter variable for loop with the same name.
You should also remove selected class from all elements before setting the clicked element 'selected'.
Try:
<script>
var tabs = document.getElementById("tabs").getElementsByTagName("li");
var panels = document.getElementById("panels").getElementsByTagName("div");
for (var i = 0; i < tabs.length; i++) {
new function(i) {
tabs[i].onclick = function() {
for (var j = 0; j < panels.length; j++) {
tabs[j].className = panels[j].className = "";
}
tabs[i].className = panels[i].className = "selected";
}
}(i);
}
</script>
You've got a couple of problems:
Multiple i variables
new function(i) {...} isn't the best syntax. I've used a closure below
multiple assignments per line isn't good
I've given your <li> elements values so that we can tell which li element has been clicked
var tabs = document.getElementById("tabs").getElementsByTagName("li");
var panels = document.getElementById("panels").getElementsByTagName("div");
for (var i = 0; i < panels.length; i++) {
(function(i) {
tabs[i].onclick = function() {
var j;
var panelIndex;
// remove styles from other tabs
for (j = 0; j < tabs.length; j++) {
tabs[j].className = "";
}
// apply style to the current tab: 'this'
this.className = "selected";
// hide other panels
for (j = 0; j < panels.length; j++) {
panels[j].className = "";
}
// show the selected panel
panelIndex = +this.value; // convert value to number
panels[panelIndex-1].className="selected"; // arrays are 0-indexed, so subtract 1
}
})(i);
}
a { text-decoration: none; }
li { list-style: none; }
li.selected { font-weight: bold; }
.panels div { display: none; }
.panels .selected { display: block; }
<div id="tabs" class="tabs">
<ul>
<li value="1" class="selected">One</li>
<li value="2" class="">Two</li>
<li value="3" class="">Three</li>
</ul>
</div>
<div id="panels" class="panels">
<div class="selected">This is panel one.</div>
<div class="">This is panel two.</div>
<div class="">This is panel three.</div>
</div>
Below here will work, as you are expecting. Two issues I found for accessing HTML Element inside for loop, you need to use .item() as its HTMLCollection you are getting instead of an array. Also your inner for loop needs to use different looping index, with one additional if condition to leave clicked one as shown and rest hidden.
<style>
a { text-decoration: none; }
li { list-style: none; }
li.selected { font-weight: bold; }
.panels div { display: none; }
.panels .selected { display: block; }
</style>
<div id="tabs" class="tabs">
<ul>
<li class="selected">One</li>
<li class="">Two</li>
<li class="">Three</li>
</ul>
</div>
<div id="panels" class="panels">
<div class="selected">This is panel one.</div>
<div class="">This is panel two.</div>
<div class="">This is panel three.</div>
</div>
<script>
var tabs = document.getElementById("tabs").getElementsByTagName("li");
var panels = document.getElementById("panels").getElementsByTagName("div");
for (var i = 0; i < tabs.length; i++) {
new function(i) {
tabs[i].onclick = function() {
tabs.item(i).className = panels.item(i).className = "selected";
for (var j = 0; j < panels.length; j++) {
if(i!=j){
tabs.item(j).className = panels.item(j).className = "";
}
}
}
}(i);
}
</script>

Categories

Resources