Currently on click of next and prev, the height of the list is adjusting. Instead of increasing and decreasing the height, i want to replace the current content with new set of content.
Expectation:
if I click on next/ prev, current visible list should replace with the new set of items with some slide animation.
Also every time I need to display 3 items, in current scenario once the next/prev iteration is completed, only 2 items are getting visible.
This is what I tried:
JS:
$(document).ready(function () {
size_li = $("#list li").size();
x=3;
$('#list li:lt('+x+')').show();
$('#next').click(function () {
x= (x+3 <= size_li) ? x+3 : size_li;
$('#list li:lt('+x+')').show();
$('#prev').show();
if(x == size_li){
$('#next').hide();
}
});
$('#prev').click(function () {
x=(x-3<0) ? 3 : x-3;
$('#list li').not(':lt('+x+')').hide();
$('#next').show();
if(x < 3){
$('#prev').hide();
}
});
});
JS Fiddle:
Demo Link
I approached the problem a bit differently. Here's the fiddle.
The gist of my solution is that I've used jQuery's animate function to do the smooth scrolling effect:
$('ul').animate({
scrollTop: $('ul').scrollTop() + height_to_show
}, 500);
One catch, however, is that the ul and the li elements need to have fixed heights. These heights are calculated internally based on the following variables set by you:
/**
* Total number of elements in the list
* #type {Number}
*/
var num_of_elems = 8;
/**
* Static height of each element (in pixels)
* #type {Number}
*/
var height_of_elem = 25;
/**
* Number of elements you want to show in the page
* #type {Number}
*/
var num_of_elems_to_show = 3;
/**
* The visible height of the ul
* #type {Number}
*/
var height_to_show = 0; //calculated internally
UPDATE
Here's the updated fiddle.
I've added functionality to hide or show the prev and next button based on the current page being displayed.
/**
* Show or hide the prev and next button depending on the current_page
*/
var show_hide_buttons = function() {
if (current_page === Math.ceil(num_of_elems / num_of_elems_to_show) - 1) {
$('#next').hide();
} else {
$('#next').show();
}
if (current_page === 0) {
$('#prev').hide();
} else {
$('#prev').show();
}
};
I know you have a solution, just wanna leave this fiddle as this is another option and little different animation.
$(document).ready(function () {
$('#list li:lt(3)').show();
$('#next').click(function() {
$('#prev').show();
var last = $('#list').children('li:visible:last');
last.nextAll('#list li:lt(3)').toggle(200);
last.next().prevAll('#list li').hide(200);
var $this = $(this);
if ($('#list li').last().is(':visible')){
$this.hide();
}
});
$('#prev').click(function() {
$('#next').show();
var first = $('#list').children('li:visible:first');
first.prevAll('#list li:lt(3)').toggle(200);
first.prev().nextAll('#list li').hide(200)
var $this = $(this);
if ($('#list li').first().is(':visible')){
$this.hide();
}
});
});
ul,li,ol{
margin: 0;
padding: 0;
list-style-type: none;
}
.l_swiper{
border: 1px solid #333;
width: 50%;
padding: 20px;
}
#list{
overflow: hidden;
max-height: 117px;
}
#list li{
display: none;
padding : 10px;
border-bottom : 1px solid #333;
}
#list li:last-child{
margin-bottom: 39px;
}
#next{
float: right;
border: 1px solid #333;
padding: 10px;
margin-top : 20px;
cursor: pointer;
}
#prev{
float: left;
border: 1px solid #333;
padding: 10px;
margin-top : 20px;
cursor: pointer;
}
.clearfix{
clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="l_swiper">
<ul id="list">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
<li>Seven</li>
<li>Eight</li>
</ul>
<div id="prev">prev</div>
<div id="next">Next</div>
<div class="clearfix"></div>
</div>
Related
Hey this is the plugin of Scrollmagic.io I am using this in my work.
But this is slow. How increase the duration time I want to change the content faster.
I looked at documentation but not much clear in docs.
Please help me out
//First the variables our app is going to use need to be declared
//References to DOM elements
var $window = $(window);
var $document = $(document);
//Only links that starts with #
var $navButtons = $("nav a").filter("[href^=#]");
var $navGoPrev = $(".go-prev");
var $navGoNext = $(".go-next");
var $slidesContainer = $(".slides-container");
var $slides = $(".slide");
var $currentSlide = $slides.first();
//Animating flag - is our app animating
var isAnimating = false;
//The height of the window
var pageHeight = $window.innerHeight();
//Key codes for up and down arrows on keyboard. We'll be using this to navigate change slides using the keyboard
var keyCodes = {
UP : 38,
DOWN: 40
}
//Going to the first slide
goToSlide($currentSlide);
/*
* Adding event listeners
* */
$window.on("resize", onResize).resize();
$window.on("mousewheel DOMMouseScroll", onMouseWheel);
$document.on("keydown", onKeyDown);
$navButtons.on("click", onNavButtonClick);
$navGoPrev.on("click", goToPrevSlide);
$navGoNext.on("click", goToNextSlide);
/*
* Internal functions
* */
/*
* When a button is clicked - first get the button href, and then slide to the container, if there's such a container
* */
function onNavButtonClick(event)
{
//The clicked button
var $button = $(this);
//The slide the button points to
var $slide = $($button.attr("href"));
//If the slide exists, we go to it
if($slide.length)
{
goToSlide($slide);
event.preventDefault();
}
}
/*
* Getting the pressed key. Only if it's up or down arrow, we go to prev or next slide and prevent default behaviour
* This way, if there's text input, the user is still able to fill it
* */
function onKeyDown(event)
{
var PRESSED_KEY = event.keyCode;
if(PRESSED_KEY == keyCodes.UP)
{
goToPrevSlide();
event.preventDefault();
}
else if(PRESSED_KEY == keyCodes.DOWN)
{
goToNextSlide();
event.preventDefault();
}
}
/*
* When user scrolls with the mouse, we have to change slides
* */
function onMouseWheel(event)
{
//Normalize event wheel delta
var delta = event.originalEvent.wheelDelta / 30 || -event.originalEvent.detail;
//If the user scrolled up, it goes to previous slide, otherwise - to next slide
if(delta < -1)
{
goToNextSlide();
}
else if(delta > 1)
{
goToPrevSlide();
}
event.preventDefault();
}
/*
* If there's a previous slide, slide to it
* */
function goToPrevSlide()
{
if($currentSlide.prev().length)
{
goToSlide($currentSlide.prev());
}
}
/*
* If there's a next slide, slide to it
* */
function goToNextSlide()
{
if($currentSlide.next().length)
{
goToSlide($currentSlide.next());
}
}
/*
* Actual transition between slides
* */
function goToSlide($slide)
{
//If the slides are not changing and there's such a slide
if(!isAnimating && $slide.length)
{
//setting animating flag to true
isAnimating = true;
$currentSlide = $slide;
//Sliding to current slide
TweenLite.to($slidesContainer, 1, {scrollTo: {y: pageHeight * $currentSlide.index() }, onComplete: onSlideChangeEnd, onCompleteScope: this});
//Animating menu items
TweenLite.to($navButtons.filter(".active"), 0.5, {className: "-=active"});
TweenLite.to($navButtons.filter("[href=#" + $currentSlide.attr("id") + "]"), 0.5, {className: "+=active"});
}
}
/*
* Once the sliding is finished, we need to restore "isAnimating" flag.
* You can also do other things in this function, such as changing page title
* */
function onSlideChangeEnd()
{
isAnimating = false;
}
/*
* When user resize it's browser we need to know the new height, so we can properly align the current slide
* */
function onResize(event)
{
//This will give us the new height of the window
var newPageHeight = $window.innerHeight();
/*
* If the new height is different from the old height ( the browser is resized vertically ), the slides are resized
* */
if(pageHeight !== newPageHeight)
{
pageHeight = newPageHeight;
//This can be done via CSS only, but fails into some old browsers, so I prefer to set height via JS
TweenLite.set([$slidesContainer, $slides], {height: pageHeight + "px"});
//The current slide should be always on the top
TweenLite.set($slidesContainer, {scrollTo: {y: pageHeight * $currentSlide.index() }});
}
}
body, div, p {
margin: 0;
padding: 0;
}
body {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 300;
letter-spacing: 0.0625em;
}
a {
text-decoration: none;
}
nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 100;
}
nav ul {
list-style: none;
text-align: center;
margin-top: 30px;
}
nav ul li {
display: inline-block;
margin-right: 20px;
}
nav ul li:last-child {
margin-right: 0;
}
#back-to-tutorial {
margin-left: 100px;
}
nav a {
position: relative;
top: 0;
padding: 10px 20px;
font-weight: normal;
font-size: 20px;
text-align: center;
border-radius: 4px;
background-color: #FFFFFF;
color: #83C78E;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
}
nav a.active {
top: -4px;
background-color: #69C773;
color: #FFFFFF;
-webkit-box-shadow: 0 4px 0 0 #51a65f;
-moz-box-shadow: 0 4px 0 0 #51a65f;
box-shadow: 0 4px 0 0 #51a65f;
}
.slides-container {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: hidden;
z-index: 10;
}
.slide {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
.slide .centered {
width: 60%;
margin: 200px auto 0;
}
.slide .centered h1 {
text-align: center;
}
.slide .centered p {
text-align: center;
margin-top: 20px;
font-size: 20px;
}
#slide-1 {
background-color: #FFFFFF;
}
#slide-2 {
background-color: #45959b;
}
#slide-3 {
background-color: #778899;
}
#slide-4 {
color: #FFFFFF;
background-color: #291F37;
}
.go-prev, .go-next {
cursor: pointer;
font-weight: bold;
text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.11.6/TweenLite.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.11.6/plugins/CSSPlugin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.11.6/plugins/ScrollToPlugin.min.js"></script>
<nav>
<ul>
<li>Slide 1</li>
<li>Slide 2</li>
<li>Slide 3</li>
<li>Slide 4</li>
</ul>
</nav>
<div class="slides-container">
<div class="slide" id="slide-1">
<div class="centered">
<h1>Fullscreen slides with GSAP</h1>
<p>Let's go to the <span class="go-next">next slide</span>.</p>
</div>
</div>
<div class="slide" id="slide-2">
<div class="centered">
<h1>It is so easy to navigate through slides</h1>
<p>You can go back to <span class="go-prev">previous slide</span> or go to the <span class="go-next">next slide</span>.</p>
</div>
</div>
<div class="slide" id="slide-3">
<div class="centered">
<h1>Use mouse wheel</h1>
<p>No, really. Try to scroll up and down with the mouse wheel to switch between slides.</p>
</div>
</div>
<div class="slide" id="slide-4">
<div class="centered">
<h1>... Or use keyboard arrows</h1>
<p>You go to previous and next slide, using up and down keyboard arrows.</p>
</div>
</div>
</div>
This is the link of scroll.io docs http://scrollmagic.io/docs/ScrollMagic.Scene.html#duration
How to apply this I bit confused please have a look
It's actually a TweenLite parameter: https://greensock.com/tweenlite
Change
TweenLite.to($slidesContainer, 1, {scrollTo: {y: pageHeight * $currentSlide.index() }, onComplete: onSlideChangeEnd, onCompleteScope: this});
To a lower value, e.g.:
TweenLite.to($slidesContainer, 0.2, {scrollTo: {y: pageHeight * $currentSlide.index() }, onComplete: onSlideChangeEnd, onCompleteScope: this});
When you click inside the input box of my to-do list and hit enter, a tiny line is added to the list. (When you enter text, the line height is regular height.) What could be causing this?
Please view my CodePen for my full code.
I'm not sure this is relevant, but here's my JavaScript:
$(function() {
$('.button').click(function() {
let toAdd = $('input[name=listItem]').val();
// Inserts li as first child of ul
$('ul').prepend('<li>' + toAdd + '</li>');
// Clears input box after clicking '+'
$('input[name=listItem]').val('');
});
// Upon hitting enter, triggers button click and prevents page from refreshing and event bubbling and capturing/trickling
$('input[name=listItem]').keypress(function(e) {
if (e.which == 13) {
$('.button').click();
e.preventDefault();
};
});
$('ul').on('click', 'li', function() {
// Upon list item click, toggleClass() adds class 'strike' for it and fadeOut() completely hides it
$(this).toggleClass('strike').fadeOut('slow');
});
});
Just check on the value you are adding:
$('.button').click(function() {
let toAdd = $('input[name=listItem]').val();
// Inserts li as first child of ul
if( toAdd == ""){
return false; // return on empty value
}
$('ul').prepend('<li>' + toAdd + '</li>');
// Clears input box after clicking '+'
$('input[name=listItem]').val('');
});
Both the below answers are right and hence upvoted but You can try and add validation to remove this situation
$(function() {
$('.button').click(function() {
let toAdd = $('input[name=listItem]').val();
if (toAdd === '') {
alert("Input should not be blank");
$('input[name=listItem]').focus();
return;
}
// Inserts li as first child of ul
$('ul').prepend('<li>' + toAdd + '</li>');
// Clears input box after clicking '+'
$('input[name=listItem]').val('');
});
// Upon hitting enter, triggers button click and prevents page from refreshing and event bubbling and capturing/trickling
$('input[name=listItem]').keypress(function(e) {
if (e.which == 13) {
$('.button').click();
e.preventDefault();
};
});
$('ul').on('click', 'li', function() {
// Upon list item click, toggleClass() adds class 'strike' for it and fadeOut() completely hides it
$(this).toggleClass('strike').fadeOut('slow');
});
});
body {
text-align: center;
background: #dfdfdf;
font-family: Helvetica;
font-size: 14px;
color: #666;
background: linear-gradient(to left, #da4453, #89216b);
}
.container {
padding: 20px;
padding-top: 5px;
width: 400px;
/* 0 is for top and bottom and auto (set to equal values for each by browser) for left-right */
margin: 0 auto;
margin-top: 40px;
background: #eee;
border-radius: 5px;
}
form {
/* Needed to display button next to input box */
display: inline-block;
}
input[type="text"] {
border: 1px solid #ccc;
height: 1.6em;
width: 29em;
color: #666;
}
/* Sets appearance of input box boundaries when user clicks inside it */
input:focus {
border-color: #da4453;
/* L to R: horizontal offset, vertical offset, blur radius. A in RGBA is alpha parameter, a number between 0.0 (fully transparent) and 1.0 (fully opaque) */
box-shadow: 0 0 8px rgba(229, 103, 23, 0.6);
outline: 0 none;
}
button.button {
margin-left: -29.8px;
/* 2px added to account for default 1px padding of input box set by user agent (browser) stylesheet */
height: -webkit-calc(1.6em + 2px);
height: calc(1.6em + 2px);
width: 25px;
color: grey;
border: none;
}
.button:hover {
cursor: pointer;
opacity: 0.8;
color: #9a9797;
}
/* Remove margins and padding from list */
ul {
margin: 0;
padding: 0;
}
/* Applies styling to any li descendants of ul (descendant combinator) */
ul li {
text-align: left;
/* Prevents default bullet points */
list-style-type: none;
margin: auto;
cursor: pointer;
position: relative;
background-color: #eee;
/* First value sets top and bottom padding; second value sets right and left */
padding: 1.5px 0;
}
/* Set all odd list items to a different color (zebra stripes) */
ul li:nth-child(odd) {
background: #f9f9f9;
}
/* Sets darker background color on hover over list items */
ul li:hover {
background-color: #ddd;
}
.strike {
text-decoration: line-through;
}
<html>
<head>
<meta charset="UTF-8">
<title>To-Do List</title>
<link rel="stylesheet" href="styles.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="designs.js"></script>
</head>
<body>
<div class="container">
<h2>To Do</h2>
<form name="listForm">
<input type="text" name="listItem" placeholder="Add new">
<button type="button" class="button">+</button>
</form>
<br><br>
<ul>
<li>Work on projects for one hour</li>
<li>Go for a walk</li>
<li>Call parents</li>
</ul>
</div>
</body>
</html>
$('.button').click(function() {
let toAdd = $('input[name=listItem]').val();
// Inserts li as first child of ul
if(toAdd == ""){
alert("Input Should no be blank");
return;
}
$('ul').prepend('<li>' + toAdd + '</li>');
// Clears input box after clicking '+'
$('input[name=listItem]').val('');
});
Try adding a check to see if there's nothing in the input box first:
$('.button').click(function() {
let toAdd = $('input[name=listItem]').val();
if (toAdd === '') return;
Using ES6 Syntax
$('.button').on('click'() => {
let toAdd = $('input[name=listItem]').val();
toAdd === '' ? return : null
The thing is that I need to make a vertical images slider,so that when i press arrow down/arrow up every image changes it's position (the highest one goes bottom,the previous take it's place)
what it should look like:
what i have got so far:
$(function(){
var $vsliderboxes = $('#vsliderboxes'),
$vslidernav = $('#vslidernav'),
boxHeight = $vsliderboxes.height(),
current_index = 0;
function clickslide(){
clearInterval(intervalTimer);
clearTimeout(timeoutTimer);
timeoutTimer = setTimeout(function () {
intervalTimer = window.setInterval(autoslide, 2000);
}, 2500);
var index = $(this).index();
current_index = index;
$vsliderboxes.children().stop().animate({
top : (boxHeight * index * -1)
}, 500);
}
function autoslide(){
current_index++;
if (current_index >= $vsliderboxes.children().children().length) {
current_index = 0;
}
$vslidernav.find('a').eq(current_index).trigger('click');
}
$vslidernav.find('a').click(clickslide);
var intervalTimer = window.setInterval(autoslide, 2000),
timeoutTimer = null;
});
#vslidernav ul {
list-style: none;
padding: 0;
}
#vslidernav ul a {
padding: 0;
cursor: pointer;
height: 50px;
}
#vslidernav ul a:active {
color: #9C9A99;
}
#vslidernav ul a li {
height: 50px;
}
#vslidernav ul .active li {
}
.#vslidernav ul a:active {
background: transparent;
color: #9C9A99;
}
.vslider {
display: inline-block;
}
#vslidernav {
float: left;
width: 100px;
z-index: 1;
height: 250px;
}
#vsliderboxes {
position : relative;
overflow : hidden;
}
#vsliderboxes div {
height: 250px;
width: 900px;
}
#vsliderboxs-inner {
position : relative;
width : 900px;
height : 250px;
}
<div class="vslider">
<div id="vslidernav">
<ul>
<a id="1">
<li><img src="img/arrtop.gif"></li>
</a>
<a id="2">
<li><img src="img/arrdown.gif"></li>
</a>
<a id="3">
<li></li>
</a>
</ul>
</div>
<div id="vsliderboxes">
<div id="vsliderboxs-inner">
<div id="box1" class="active"><img src="img/slide1.gif"></div>
<div id="box2" class="inactive"><img src="img/slide2.gif"></div>
<div id="box3" class="inactive"><img src="img/slide3.gif"></div>
</div>
</div>
</div>
thanks for any advice
I think, that it isn't possible to solve this issue like you try to.
Because, when you work with the "top" property, you can't take one image from the top and append it to the other end because appending the image, will move the other images to another place --> the top property wouldn't be correct any more.
I think the contributed sliders (e.g. http://www.jssor.com/demos/vertical-slider.slider) work with the transform CSS property.
transform: translate3d()
Try to research about this property.
Roko C. Buljan answered on this page: loop carousel jquery
He uses a scrollTop loop for your problem.
I've also written a simple slider some time ago. I have now implemented the Roku C. Buljan method. Feel free to look at my code on Bitbucket.
https://bitbucket.org/d-stone/jqueryslider
An excerpt may help you:
value = prev_or_next == 'next' ? self.globals.slide_height : 0;
last = $('#container').find('> div:last');
first = $('#container').find('> div:first');
if(prev_or_next == 'prev') { // click on "next"-button
first.before(last); // put last element before first
settings.elements.inner.scrollTop(self.globals.slide_height); // set the scrollTop to 1 slide-height
}
// animation itself:
$('#container').stop().animate({scrollTop: value}, {
duration: settings.slide_speed,
done: function() {
if(prev_or_next == 'next') {
// put first item after last
last.after(first);
}
}
});
I'd advise you to validate your HTML (W3C Validator). There are some errors inside.
Invalid HTML can be the reason for some CSS and Javascript Errors.
I'm trying to have a bgcolor change for an element on mouseover, mouseout, and onclick. The problem is Javascript overwrites my onclick with mouseout, so I can't have both. So is there any way to have mouseover reset after mouseout?
function init() {
document.getElementById('default').onmouseover = function() {
tabHoverOn('default', 'grey')
};
document.getElementById('default').onmouseout = function() {
tabHoverOff('default', 'yellow')
};
document.getElementById('section2').onmouseover = function() {
tabHoverOn('section2', 'grey')
};
document.getElementById('section2').onmouseout = function() {
tabHoverOff('section2', 'yellow')
};
document.getElementById('section3').onmouseover = function() {
tabHoverOn('section3', 'grey')
};
document.getElementById('section3').onmouseout = function() {
tabHoverOff('section3', 'yellow')
};
}
function tabHoverOn(id, bgcolor) {
document.getElementById(id).style.backgroundColor = bgcolor;
}
function tabHoverOff(id, bgcolor) {
document.getElementById(id).style.backgroundColor = bgcolor;
}
var current = document.getElementById('default');
function tab1Highlight(id) {
if (current != null) {
current.className = "";
}
id.className = "tab1highlight";
current = id;
}
function tab2highlight(id) {
if (current != null) {
current.className = "";
}
id.className = "tab2highlight";
current = id;
}
function tab3highlight(id) {
if (current != null) {
current.className = "";
}
id.className = "tab3highlight";
current = id;
}
window.onload = init();
body {
width: 900px;
margin: 10px auto;
}
nav {
display: block;
width: 80%;
margin: 0 auto;
}
nav > ul {
list-style: none;
}
nav > ul > li {
display: inline-block;
margin: 0 3px;
width: 150px;
}
nav > ul > li > a {
width: 100%;
background-color: #ffff66;
border: 1px solid #9b9b9b;
border-radius: 12px 8px 0 0;
padding: 8px 15px;
text-decoration: none;
font-weight: bold;
font-family: arial, sans-serif;
}
main {
display: block;
width: 80%;
margin: 0 auto;
border: 1px solid #9b9b9b;
padding: 10px;
}
main > h1 {
font-size: 1.5em;
}
.tab1highlight {
background-color: #339966;
color: white;
}
.tab2highlight {
background-color: #ff6666;
color: white;
}
.tab3highlight {
background-color: #6600ff;
color: white;
}
main img {
border: 5px solid #eeefff;
width: 80%;
margin-top: 20px;
}
<body>
<nav>
<ul>
<li>Section 1</li>
<li>Section 2</li>
<li>Section 3</li>
</ul>
</nav>
<main>
<h1>Exercise: Navigation Tab #5</h1>
<ul>
<li>
Combine the navigation tab exercises #1, #3, and #4 in one file, including <br>
<ul>
<li>temporarily change the background color of a tab when the cursor is hovering on it.</li>
<li>set the foreground and background color of the tab being clicked.</li>
<li>change the background color of the main element based on the selected tab.</li>
</ul>
<p>
To test, click on a tab and then move your mouse around. For example, the third tab is clicked, the tab background color is switched to blue. Then hover the mouse over the third tab, the background color of the tab should be switch to light green and then back to blue after the mouse moves out.
</p>
<img src="menu_tab5.jpg">
</li>
</ul>
</main>
It's generally a good idea to keep CSS out of JavaScript completely if you can help it. A better strategy for solving the hover problem is to use the CSS pseudo selector :hover rather than coding the color changes in JavaScript. If you give all your tabs the same class, you only have to write the CSS once:
.tab {
background-color: yellow;
}
.tab:hover {
background-color: grey;
}
Once you've done that, you can also relegate the click styling to CSS by creating an event handler that adds and removes a special class each time a tab is clicked.
In the CSS file:
.tab.clicked {
background-color: blue;
}
And then in JavaScript, something like:
var tabs = document.getElementsByClassName('tab');
for (i = 0; i < tabs.length; i ++) {
tabs[i].onclick = function (ev) {
for (i = 0; i < tabs.length; i ++) {
tabs[i].classList.remove('clicked');
}
ev.currentTarget.classList.add('clicked');
};
}
I've created a JSFiddle to illustrate.
Try updating a Boolean variable.
var Ele = document.getElementById('default');
var clicked = false;
Ele.onclick = function(){
clicked = true;
// add additional functionality here
}
Ele.onmouseover = function(){
clicked = false;
// add additional functionality here
}
Ele.onmouseout = function(){
if(!clicked){
// add additional functionality here
}
}
This is my JSFiddle
As you can see from the fiddle that there is a list that is being scrolled with the help of arrows.. So what I want is to animate that transition when the list visible and hidden.
I don't know about the animation. I have seen many examples and tried to adjust them with my example but it's not working... How do I get the list to animate?
$(document).ready(function(){
var code='';
for(var i=1;i<=20;i++)
{
code+="<li>list Item "+i+"</li>";
}
$('#list-items').html(code);
});
var list_items = [];
var index = 0;
var list_length = 0;
function getAllListItems() {
var temp = document.getElementsByTagName('li');
for (i = 0; i < temp.length; i++) {
list_items.push(temp[i]);
}
list_length = temp.length;
}
getAllListItems();
function move(dir) {
if (dir == left) {
list_items[index].style.display = 'block';
index--;
if (index < 0) {
index = 0;
}
} else if (dir == right) {
list_items[index].style.display = 'none';
if (index >= ((list_length) - 1)) {
index = (list_length) - 1;
} else {
index++;
}
} else {}
}
* {
box-sizing: border-box;
}
ul {
float:left;
height:50px;
width: 600px;
overflow: hidden;
}
ul li {
text-align: center;
border: 2px solid black;
width: 100px;
height: 50px;
float: left;
list-style-type: none;
background-color: aquamarine;
}
ul li:first-child {
display: block;
}
#left, #right {
float:left;
height:50px;
background-color:aqua;
font-size:2em;
padding-left: 20px;
padding-right:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload='getAllListItems()'>
<div id='t'></div>
<button id='left' onClick="move(left)">
<</button>
<ul id='list-items'>
</ul>
<button id='right' onClick='move(right)'>></button>
</body>
You can easily just replace your lines:
list_items[index].style.display = 'block';
list_items[index].style.display = 'none';
with the jQuery show() and hide() functions:
$(list_items[index]).show("slow");
$(list_items[index]).hide("slow");
As demonstrated in my updated version of your Fiddle
For different transitions, you can use the animate() function, which lets you tell it what css properties to affect. In addition to numeric values, jQuery also supports the special values 'show', 'hide', and 'toggle' (which, incidentally, will show, hide, or toggle the show/hide status of an element using that property). So for instance, if you wanted to shrink them only horizontally and leave the vertical alone, you could change the .show() and .hide() calls to:
$(list_items[index]).animate({width:'show'}, 600);
$(list_items[index]).animate({width:'hide'}, 600);
I've demonstrated this in another updated Fiddle