<br> mucking up .next() in JQuery - javascript

I am hacking together an experimental pagination interface called wigi(board) but have run into an issue.
The interface works by any l1 (subject) class or l2 (subheading) class running vertical down the left. Pages (l3 class nodes) are represented as points attached to the side of an l1 or l2.
Mousing over any node will move the selector to that node and call a db query to display a specific page's contents. This works fine. It moves like it should.
Right now I have buttons that will also move between the next and previous li in the navigation list. These are filler for future swiping and other interaction to demonstrate the issue.
Right now these buttons work to a point, until the jquery .next() hits a <br> node, which I am using in order to break the l3 lines and continue the menu vertical to the next l1 or l2. When the .next hits the last node before one of these, it stops dead and wont jump down to the next row. Why? What is the best strategy to fix it?
JS fiddle: http://jsfiddle.net/93g786jp/
The issue with next is in here. It is running over an li list (best to look at JSfiddle)
function nextAndBack(e) {
var cur = $('.dots .selected'),
next = cur.next('li'),
prev = cur.prev('li');
if (e.target.id == 'nextButton') {
if (next.length == 1) {
newSelected(next);
console.log("Next Node:")
console.log(next);
$(next).trigger("mouseover");
}
} else if (e.target.id == 'prevButton') {
if (prev.length == 1) {
newSelected(prev);
console.log("Previous Node:")
console.log(prev);
$(prev).trigger("mouseover");
}
}
}
Note this is based on the gooey interface by Lucas Bebber # https://codepen.io/lbebber/pen/lFdHu which was the closet match I could find for an interface like what I wanted. For the posted example, I stripped out any effects and other extras so some stubs exist.

As the <br /> gets in the way of selecting siblings you can instead use nextAll() or prevAll() and then get the first() of the selected items:
next = cur.nextAll('li').first(),
prev = cur.prevAll('li').first();
function wigiBoardMove() {
var cur = $(this);
var desty = cur.position().top;
var destx = cur.position().left;
var t = 0.6;
gsap.to($(".select"), t, {
y: desty,
ease: Back.easeOut
});
gsap.to($(".select"), t, {
x: destx,
ease: Back.easeOut
});
newSelected(cur);
}
function newSelected(newTarget) {
$('.selected').removeClass('selected');
newTarget.addClass('selected');
}
function nextAndBack(e) {
var cur = $('.dots .selected'),
next = cur.nextAll('li').first(),
prev = cur.prevAll('li').first();
if (e.target.id == 'nextButton') {
if (next.length == 1) {
newSelected(next);
$(next).trigger("mouseover");
}
} else if (e.target.id == 'prevButton') {
if (prev.length == 1) {
newSelected(prev);
$(prev).trigger("mouseover");
}
}
}
/* Modified from gooey pagnation code published by Lucas Bebber # https://codepen.io/lbebber/pen/lFdHu */
$(function() {
$(".dot").on("mouseenter", wigiBoardMove);
var lastPos = $(".select").position().top;
function updateScale() {
var pos = $(".select").position().top;
var speed = Math.abs(pos - lastPos);
var d = 44;
var offset = -20;
var hd = d / 2;
var scale = (offset + pos) % d;
if (scale > hd) {
scale = hd - (scale - hd);
}
scale = 1 - ((scale / hd) * 0.35);
gsap.to($(".select"), 0.1, {
scaleY: 1 + (speed * 0.06),
scaleX: scale
})
lastPos = pos;
requestAnimationFrame(updateScale);
}
requestAnimationFrame(updateScale);
$(".dot:eq(0)").trigger("mouseover");
// Back and Forward Node Logic
$('#nextButton, #prevButton').on('click', nextAndBack);
})
#container {}
.dots {
list-style-type: none;
padding: 0;
margin: 0;
padding-top: 20px;
padding-bottom: 20px;
padding-left: 20px;
margin-left: -10px;
padding-right: 10px;
position: absolute;
top: 0px;
width: 150px;
right: 0px;
}
.dot {
display: inline-block;
vertical-align: middle;
margin-left: 5px;
margin-right: 5px;
cursor: pointer;
color: white;
position: relative;
z-index: 2;
}
.l1 {
border-radius: 100%;
width: 10px;
height: 10px;
background: blue;
border: none;
}
.l3 {
border-radius: 100%;
width: 7px;
height: 7px;
border: none;
background: blue;
}
.select {
display: block;
border-radius: 100%;
width: 15px;
height: 15px;
background: #daa520;
position: absolute;
z-index: 3;
top: -4px;
left: 1px;
pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.5.1/gsap.min.js"></script>
<div id="container">
<ul class="dots">
<li class="select"></li>
<li class="dot l1"></li>
<li class="dot l3"></li>
<li class="dot l3"></li>
<li class="dot l3"></li><br>
<li class="dot l1"></li>
<li class="dot l3"></li>
<li class="dot l3"></li><br>
<li class="dot l1"></li>
<li class="dot l3"></li><br>
</ul>
<img id="nextButton" height="10" width="10" alt="Next Node" /><br>
<img id="prevButton" height="10" width="10" alt="Previous Node" />
</div>

Related

What could be the bare minimum steps to animate the following carousel implementation?

I am making a vanilla js carousel. I have laid out basic previous and next functionality using js along with html and css.
Now I tried to use css-animations (keyframes) to do left and right slide-in/slide-out animations but the code became messy for me. So here I am asking that what minimal changes would be needed to get the same animation effects in this implementation ?
Will you go for pure JS based or pure CSS based or a mix to do the same ?
My goal is get proper animation with minimal code.
(function () {
let visibleIndex = 0;
let carousalImages = document.querySelectorAll(".carousal__image");
let totalImages = [...carousalImages].length;
function makeNextVisible() {
visibleIndex++;
if (visibleIndex > totalImages - 1) {
visibleIndex = 0;
}
resetVisible();
renderVisible();
}
function makePrevVisible() {
visibleIndex--;
if (visibleIndex < 0) {
visibleIndex = totalImages - 1;
}
resetVisible();
renderVisible();
}
function resetVisible() {
for (let index = 0; index < totalImages; index++) {
carousalImages[index].className = "carousal__image";
}
}
function renderVisible() {
carousalImages[visibleIndex].className = "carousal__image--visible";
}
function renderCarousel({ autoplay = false, autoplayTime = 1000 } = {}) {
if (autoplay) {
[...document.querySelectorAll("button")].forEach(
(btn) => (btn.style.display = "none")
);
setInterval(() => {
makeNextVisible();
}, autoplayTime);
} else renderVisible();
}
renderCarousel();
// Add {autoplay:true} as argument to above to autplay the carousel.
this.makeNextVisible = makeNextVisible;
this.makePrevVisible = makePrevVisible;
})();
.carousal {
display: flex;
align-items: center;
}
.carousal__wrapper {
width: 500px;
height: 400px;
}
.carousal__images {
display: flex;
overflow: hidden;
list-style-type: none;
padding: 0;
}
.carousal__image--visible {
position: relative;
}
.carousal__image {
display: none;
}
<div class='carousal'>
<div class='carousal__left'>
<button onclick='makePrevVisible()'>Left</button>
</div>
<section class='carousal__wrapper'>
<ul class='carousal__images'>
<li class='carousal__image'>
<img src='https://fastly.syfy.com/sites/syfy/files/styles/1200x680/public/2018/03/dragon-ball-super-goku-ultra-instinct-mastered-01.jpg?offset-x=0&offset-y=0' alt='UI Goku' / width='500' height='400'/>
</li>
<li class='carousal__image'>
<img src='https://www.theburnin.com/wp-content/uploads/2019/01/super-broly-3.png' alt='Broly Legendary' width='500' height='400'/>
</li>
<li class='carousal__image'>
<img src='https://lh3.googleusercontent.com/proxy/xjEVDYoZy8-CTtPZGsQCq2PW7I-1YM5_S5GPrAdlYL2i4SBoZC-zgtg2r3MqH85BubDZuR3AAW4Gp6Ue-B-T2Z1FkKW99SPHwAce5Q_unUpwtm4' alt='Vegeta Base' width='500' height='400'/>
</li>
<li class='carousal__image'>
<img src='https://am21.mediaite.com/tms/cnt/uploads/2018/09/GohanSS2.jpg' alt='Gohan SS2' width='500' height='400'/>
</li>
</ul>
</section>
<div class='carousal__right'>
<button onclick='makeNextVisible()'>Right</button>
</div>
</div>
Updated codepen with feedback from the below answers and minor additional functionalities = https://codepen.io/lapstjup/pen/RwoRWVe
I think the trick is pretty simple. ;)
You should not move one or two images at the same time. Instead you should move ALL images at once.
Let's start with the CSS:
.carousal {
position: relative;
display: block;
}
.carousal__wrapper {
width: 500px;
height: 400px;
position: relative;
display: block;
overflow: hidden;
margin: 0;
padding: 0;
}
.carousal__wrapper,
.carousal__images {
transform: translate3d(0, 0, 0);
}
.carousal__images {
position: relative;
top: 0;
left: 0;
display: block;
margin-left: auto;
margin-right: auto;
}
.carousal__image {
float: left;
height: 100%;
min-height: 1px;
}
2nd step would be to calculate the maximum width for .carousal__images. For example in your case 4 * 500px makes 2000px. This value must be added to your carousal__images as part of the style attribute style="width: 2000px".
3rd step would be to calculate the next animation point and using transform: translate3d. We start at 0 and want the next slide which means that we have slide to the left. We also know the width of one slide. So the result would be -500px which also has to be added the style attribute of carousal__images => style="width: 2000px; transform: translate3d(-500px, 0px, 0px);"
That's it.
Link to my CodePen: Codepen for Basic Carousel with Autoplay
Try this. First stack all the images next to each other in a div and only show a single image at a time by setting overflow property to hidden for the div. Next, add event listeners to the buttons. When a bottom is clicked, the div containing the images is translated by -{size of an image} * {image number} on the x axis. For smooth animation, add transition: all 0.5s ease-in-out; to the div.
When someone clicks left arrow on the first image, the slide should display the last image. So for that counter is set to {number of images} - 1 and image is translated to left size * counter px.
For every click on the right arrow, the counter is incremented by 1 and slide is moved left. For every click on the left arrow, the counter is decremented by 1.
Slide.style.transform = "translateX(" + (-size * counter) + "px)"; this is the condition which is deciding how much the slide should be translated.
const PreviousButton = document.querySelector(".Previous-Button");
const NextButton = document.querySelector(".Next-Button");
const Images = document.querySelectorAll("img");
const Slide = document.querySelector(".Images");
const size = Slide.clientWidth;
var counter = 0;
// Arrow Click Events
PreviousButton.addEventListener("click", Previous);
NextButton.addEventListener("click", Next);
function Previous() {
counter--;
if (counter < 0) {
counter = Images.length - 1;
}
Slide.style.transform = "translateX(" + (-size * counter) + "px)";
}
function Next() {
counter++;
if (counter >= Images.length) {
counter = 0;
}
Slide.style.transform = "translateX(" + (-size * counter) + "px)";
}
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
.Container {
width: 60%;
margin: 0px auto;
margin-top: 90px;
overflow: hidden;
position: relative;
}
.Container .Images img {
width: 100%;
}
.Images {
transition: all 0.5s ease-in-out;
}
.Container .Previous-Button {
position: absolute;
background: transparent;
border: 0px;
outline: 0px;
top: 50%;
left: 20px;
transform: translateY(-50%);
filter: invert(80%);
z-index: 1;
}
.Container .Next-Button {
position: absolute;
background: transparent;
border: 0px;
outline: 0px;
top: 50%;
right: 20px;
transform: translateY(-50%);
filter: invert(80%);
z-index: 1;
}
.Container .Images {
display: flex;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/css2?family=Cabin&family=Poppins&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<title>Carousel</title>
</head>
<body>
<div class="Container">
<button class="Previous-Button">
<svg style = "transform: rotate(180deg);" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M8.122 24l-4.122-4 8-8-8-8 4.122-4 11.878 12z"/></svg>
</button>
<button class="Next-Button">
<svg xmlns="http://www.w3.org/2000/svg" width = "24" height = "24" viewBox = "0 0 24 24"><path d="M8.122 24l-4.122-4 8-8-8-8 4.122-4 11.878 12z"/></svg>
</button>
<div class="Images">
<img src="https://source.unsplash.com/1280x720/?nature">
<img src="https://source.unsplash.com/1280x720/?water">
<img src="https://source.unsplash.com/1280x720/?rock">
<img src="https://source.unsplash.com/1280x720/?abstract">
<img src="https://source.unsplash.com/1280x720/?nature">
<img src="https://source.unsplash.com/1280x720/?trees">
<img src="https://source.unsplash.com/1280x720/?human">
<img src="https://source.unsplash.com/1280x720/?tech">
</div>
</div>
<script src="main.js"></script>
</body>
</html>

Random name picker with bounce animation

I'm looking to create a random name picker with HTML, JS and CSS which has gone quite well as you can see here... http://clients.random.agency/namepicker/
However, the client has asked for it to have a similar animation to this with ...
https://www.dropbox.com/s/3likecb0ld30som/Jv0Gp4XkhQ.mp4?dl=0
I've search google but I can't seem to find any examples of what I'm looking for and would really appreciate if anyone could point me in the right direction.
This is a simple example, hope be helpful.
var names =['John', 'David', 'Joe', 'Sara'];
var nameCount= names.length;
var p = document.getElementById("container");
var randTimer = setInterval(function(){ p.innerHTML = names[Math.floor(Math.random() * nameCount)]; }, 200);
function stop(){
clearInterval(randTimer);
}
#container{
color: red;
font-size:2rem;
text-align:center;
cursor: pointer;
}
<p id="container" onClick="stop()"></p>
<p>click on random names to pick one!</P>
Here's a pretty similar example I was able to find. Using Javascript seems to be the most straightforward way to go about doing this. https://codepen.io/maerianne/pen/pRQbQr
var myScrollTop = function(elem, delay){
elem.animate({ scrollTop: 0 }, delay, function(){
myScrollBottom(elem, delay);
});
};
var myScrollBottom = function(elem, delay){
elem.animate({ scrollTop: elem.height() }, delay, function(){
myScrollTop(elem, delay);
});
};
var scrollUpDown = function(elem, delay) {
myScrollTop(elem, delay);
};
$(document).ready(function(){
scrollUpDown($(".scroll-up-down"), 5000);
});
As you can see, scrollUpDown()is the initial function which starts a loop switching between myScrollTop() and myScrollBottom(). You could pretty easily make the delay increase with each iteration to mimic the slowing down and eventual stop in the example animation you gave.
You could also refactor this to be a singular recursive function.
Best of luck!
It picks a random item from the array of labels. Then it goes into a loop, changing the label to the next item in the array until it gets to the chosen one, and using animation for the transitions
$('#search_btns button:nth-child(2)').hover(function() {
btnTimeID = setTimeout(function() {
// We are using the math object to randomly pick a number between 1 - 11, and then applying the formula (5n-3)5 to this number, which leaves us with a randomly selected number that is applied to the <ul> (i.e. -185) and corresponds to the position of a word (or <li> element, i.e. "I'm Feeling Curious").
var pos = -((Math.floor((Math.random() * 11) + 1)) * 5 - 3) * 5
if (pos === -135) {
console.log("position didn't change, let's force change")
pos = -35;
}
$('#search_btns button:nth-child(2) ul').animate({'bottom':pos + 'px'}, 300);
// Change the width of the button to fit the currently selected word.
if (pos === -35 || pos === -110 || pos === -185 || pos === -10 || pos === -60 || pos === -160) {
console.log(pos + ' = -35, -110, -185, -10, -60, -160');
$('#search_btns button:nth-child(2)').css('width', '149px');
} else if (pos === -85) {
console.log(pos + ' = -85');
$('#search_btns button:nth-child(2)').css('width', '160px');
} else if (pos === -210) {
console.log(pos + ' = -210');
$('#search_btns button:nth-child(2)').css('width', '165px');
} else {
console.log(pos + ' = -260, -235');
$('#search_btns button:nth-child(2)').css('width', '144px');
}
},200);
}, function() {
clearTimeout(btnTimeID);
setTimeout(function() {
console.log('setTimeout function');
$('#search_btns button:nth-child(2) ul').css('bottom', '-135px'); // this is the original position
$('#search_btns button:nth-child(2)').css('width', '144px'); // reset the original width of the button
},200);
});
body, html {
margin: 0;
box-sizing: border-box;
font-family: arial;
}
*, *:before, *:after {
box-sizing: inherit;
}
#search_btns {
width: 400px;
margin: 30px auto;
padding-left: 60px;
}
#search_btns button:nth-child(2) {
width: 144px;
}
#search_btns button:nth-child(1) {
bottom: 12px;
}
#search_btns button {
position: relative;
height: 34px;
margin: 3px;
font-weight: bold;
color: gray;
background: #f1f1f1;
border: 1px solid #f1f1f1;
border-radius: 2px;
padding: 0 15px;
overflow: hidden;
}
#search_btns button:hover {
color: black;
border: 1px solid #bdbdbd;
box-shadow: 0px 0.5px 0px 0px #d3d3d3;
}
#search_btns button:active {
border: 1px solid #7f7fff;
}
#search_btns button:focus {
outline: 0;
}
#search_btns button ul li {
list-style-type: none;
padding: 5px 0;
text-align: left;
}
#search_btns button ul {
padding-left: 0;
position: absolute;
bottom: -135px;
width: 144px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="search_btns">
<button>This might be the effect you looking for</button>
<button>
<ul>
<li>item0/li>
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
<li>item6</li>
<li>item7</li>
<li>item8</li>
<li>item9</li>
</ul>
</button>
</div>
</body>
</html>

Adapt vanilla js carousel to ie

I'm building a website that uses a carousel like this one:
https://codepen.io/queflojera/pen/RwwLbEY?editors=1010
It works perfectly on opera, chrome, edge but it stops working on ie and I need it to work on ie as well, if anyone knows any way around I'll really appreciate it.
//I'm not pretty sure what is causing the ie failure on this code
// Select the carousel you'll need to manipulate and the buttons you'll add events to
const carousel = document.querySelector("[data-target='carousel']");
const card = carousel.querySelector("[data-target='card']");
const leftButton = document.querySelector("[data-action='slideLeft']");
const rightButton = document.querySelector("[data-action='slideRight']");
// Prepare to limit the direction in which the carousel can slide,
// and to control how much the carousel advances by each time.
// In order to slide the carousel so that only three cards are perfectly visible each time,
// you need to know the carousel width, and the margin placed on a given card in the carousel
const carouselWidth = carousel.offsetWidth;
const cardStyle = card.currentStyle || window.getComputedStyle(card)
const cardMarginRight = Number(cardStyle.marginRight.match(/\d+/g)[0]);
// Count the number of total cards you have
const cardCount = carousel.querySelectorAll("[data-target='card']").length;
// Define an offset property to dynamically update by clicking the button controls
// as well as a maxX property so the carousel knows when to stop at the upper limit
let offset = 0;
const maxX = -((cardCount) * carouselWidth +
(cardMarginRight * cardCount) -
carouselWidth - cardMarginRight);
// Add the click events
leftButton.addEventListener("click", function() {
if (offset !== 0) {
offset += carouselWidth + cardMarginRight;
carousel.style.transform = `translateX(${offset}px)`;
}
})
rightButton.addEventListener("click", function() {
if (offset !== maxX) {
offset -= carouselWidth + cardMarginRight;
carousel.style.transform = `translateX(${offset}px)`;
}
})
.wrapper {
height: 200px;
width: 632px;
position: relative;
overflow: hidden;
margin: 0 auto;
}
.button-wrapper {
width: 100%;
height: 100%;
display: flex;
justify-content: space-between;
align-items: center;
position: absolute;
}
.carousel {
margin: 0;
padding: 0;
list-style: none;
width: 100%;
display: flex;
position: absolute;
left: 0;
transition: all .5s ease;
}
.card {
background: black;
min-width: 632px;
height: 200px;
display: inline-block;
}
.card:nth-child(odd) {
background-color: blue;
}
.card:nth-child(even) {
background-color: red;
}
<div class="wrapper">
<ul class="carousel" data-target="carousel">
<li class="card" data-target="card">1</li>
<li class="card" data-target="card">2</li>
<li class="card" data-target="card">3</li>
<li class="card" data-target="card">4</li>
<li class="card" data-target="card">5</li>
<li class="card" data-target="card">6</li>
<li class="card" data-target="card">7</li>
<li class="card" data-target="card">8</li>
<li class="card" data-target="card">9</li>
</ul>
<div class="button-wrapper">
<button data-action="slideLeft">L</button>
<button data-action="slideRight">R</button>
</div>
</div>
Invalid character
carousel.style.transform = `translateX(${offset}px)`;
IE does not support template literals (backticks)
To fix use
carousel.style.transform = "translateX("+offset+"px)";
Also getting
Unable to get property '0' of undefined or null reference
because it is auto in IE
const cardMarginRight = Number(cardStyle.marginRight.match(/\d+/g)[0]);
Fix:
const marginRight = cardStyle.marginRight;
const cardMarginRight = isNaN(parseInt(marginRight)) ? 0 : Number(cardStyle.marginRight.match(/\d+/g)[0]);
//I'm not pretty sure what is causing the ie failure on this code
// Select the carousel you'll need to manipulate and the buttons you'll add events to
const carousel = document.querySelector("[data-target='carousel']");
const card = carousel.querySelector("[data-target='card']");
const leftButton = document.querySelector("[data-action='slideLeft']");
const rightButton = document.querySelector("[data-action='slideRight']");
// Prepare to limit the direction in which the carousel can slide,
// and to control how much the carousel advances by each time.
// In order to slide the carousel so that only three cards are perfectly visible each time,
// you need to know the carousel width, and the margin placed on a given card in the carousel
const carouselWidth = carousel.offsetWidth;
const cardStyle = card.currentStyle || window.getComputedStyle(card)
const marginRight = cardStyle.marginRight;
const cardMarginRight = isNaN(parseInt(marginRight)) ? 0 : Number(cardStyle.marginRight.match(/\d+/g)[0]);
// Count the number of total cards you have
const cardCount = carousel.querySelectorAll("[data-target='card']").length;
// Define an offset property to dynamically update by clicking the button controls
// as well as a maxX property so the carousel knows when to stop at the upper limit
let offset = 0;
const maxX = -((cardCount) * carouselWidth +
(cardMarginRight * cardCount) -
carouselWidth - cardMarginRight);
// Add the click events
leftButton.addEventListener("click", function() {
if (offset !== 0) {
offset += carouselWidth + cardMarginRight;
carousel.style.transform = "translateX("+offset+"px)";
}
})
rightButton.addEventListener("click", function() {
if (offset !== maxX) {
offset -= carouselWidth + cardMarginRight;
carousel.style.transform = "translateX("+offset+"px)";
}
})
.wrapper {
height: 200px;
width: 632px;
position: relative;
overflow: hidden;
margin: 0 auto;
}
.button-wrapper {
width: 100%;
height: 100%;
display: flex;
justify-content: space-between;
align-items: center;
position: absolute;
}
.carousel {
margin: 0;
padding: 0;
list-style: none;
width: 100%;
display: flex;
position: absolute;
left: 0;
transition: all .5s ease;
}
.card {
background: black;
min-width: 632px;
height: 200px;
display: inline-block;
}
.card:nth-child(odd) {
background-color: blue;
}
.card:nth-child(even) {
background-color: red;
}
<div class="wrapper">
<ul class="carousel" data-target="carousel">
<li class="card" data-target="card">1</li>
<li class="card" data-target="card">2</li>
<li class="card" data-target="card">3</li>
<li class="card" data-target="card">4</li>
<li class="card" data-target="card">5</li>
<li class="card" data-target="card">6</li>
<li class="card" data-target="card">7</li>
<li class="card" data-target="card">8</li>
<li class="card" data-target="card">9</li>
</ul>
<div class="button-wrapper">
<button data-action="slideLeft">L</button>
<button data-action="slideRight">R</button>
</div>
</div>

Style is being added to the last child among a set of elements, instead of the last child of the selected element

var NavLinks = document.querySelectorAll('.nav-link');
var circuses = document.querySelectorAll('.circle');
for (var i = 0; i < NavLinks.length; i++) {
var navLink = NavLinks[i];
navLink.addEventListener('click', function () {
for (var i = 0; i < circuses.length; i++) {
var circle = circuses[i];
circle.style.display='none';
}
var theLastChild = navLink.lastChild;
theLastChild.style.display='block';
}
);
}
.nav-container{
height: 10px;
background: white;
padding: 30px 0px 40px 0px;
margin-left: 18%;
margin-right: 18%;
}
.nav-body ul{
text-align: right;
}
.nav-body ul li{
display: inline- block;
float: left;
margin-right: 30px;
}
#logo{
margin-right: 0px;
}
.nav-body ul li{
line-height: 0.6;
}
#logo{
margin-top: -10px;
}
#logo-light-blue{
color: #5dc5ef;
font-weight: 900;
}
#logo-dark-blue{
color: #1885c8;
font-weight: 900;
}
.circle {
display: none;
width: 8px;
height: 8px;
background: #5dc5ef;
/* -moz-border-radius: 50px;
-webkit-border-radius: 50px; */
border-radius: 4px;
margin: auto;
margin-top: 7px;
}
<header class="nav-container">
<nav class="nav-body">
<ul>
<li class="nav-link">צור קשר
<div class="circle"></div></li>
<li class="nav-link">המלצות ומאמרים
<div class="circle"></div></li>
<li class="nav-link">שאלות נפוצות
<div class="circle"></div></li>
<li class="nav-link">אודות ד"ר שי מרון אלדר
<div class="circle"></div></li>
<li class="nav-link">אודות ההליכים
<div class="circle"></div></li>
<li class="nav-link">ראשי
<div class="circle"></div></li>
<li id="logo"> <h3> <span id="logo-light-blue"> ד"ר </span><span id="logo-dark-blue"> שי מרון אלדר </span></h3><br>
<h6> פתרונות כירורגיים להשמנת יתר וניתוחים זעיר פולשניים</h6></li>
</ul>
</nav>
</header>
I need to make a blue circle under that category menu, which I pressed. But now blue circle added only to last menu category. Doesn't matter which one was pressed.
I looking for the last child of that menu category which was pressed. But it shows me every time last child of all menu categories.
What is wrong?
>
You have errors in HTML. Span tags need to be closed.
<li id="logo">
<h3>
<span id="logo-light-blue"> ד"ר </span>
<span id="logo-dark-blue"> שי מרון אלדר </span>
</h3>
<br>
<h6> פתרונות כירורגיים להשמנת יתר וניתוחים זעיר פולשניים</h6>
</li>
And Id attributes should be unique to the element, you are repeating the circle as an Id all over the place.
<div id="circle"></div></li>
It this doesn't solve it, try explaining the question better since even in the demo you have put result is all over the place. Are we missing some CSS or a style lib?
EDIT: I think I know what you wanna, is it this? Have a look at fiddle:
fiddle here
Do you need circle removed from other elements once you click your element?
If you need the circle to be only on 1 element, it needs to be removed from others.
Here is a fiddle showing that:
fiddle with only 1 circle
Difference is in:
var NavLinks = document.querySelectorAll('.nav-link');
for (var i = 0; i < NavLinks.length; i++) {
var navLink = NavLinks[i];
navLink.addEventListener('click', function (event) {
var allNavs = document.querySelectorAll('.nav-link div');
for (var it = 0; it < allNavs.length; it++){
console.log(allNavs[it]);
allNavs[it].classList.add('invisible');
allNavs[it].classList.remove('circleVisible');
}
console.log(allNavs);
var targetElement = event.target || event.srcElement;
var circleDiv = targetElement.parentNode.querySelectorAll('div');
console.log(circleDiv[0]);
circleDiv[0].classList.add('circleVisible');
circleDiv[0].classList.remove('invisible');
console.log(circleDiv[0]);
}
);
}
I have left console.logs, so you see how it works, remove them when running the code for real :)
The first big problem I see is you have nested for loops but are using the same iterator variable of i. If you are going to next the loops, you need the inner loop to have a different variable. In situations like this, I will often use ii just because it's easy.
Furthermore, you seem to be doing this in a roundabout way. I'm not entirely sure what you need, but if it is as it appears, then this solution is simpler.
CSS
.circle {
display: none;
... other attributes
}
.active-menu-item > .circle {
display: block;
}
JavaScript
var NavLinks = document.querySelectorAll('.nav-link');
for (var i = 0; i < NavLinks.length; i++) {
var navLink = NavLinks[i];
navLink.addEventListener('click', function () {
for (var ii = 0; ii < NavLinks.length; ii++) {
NavLinks[ii].classList.remove("active-menu-item");
}
navLink.classList.add("active-menu-item");
});
}

Correcting the sliding animation of a custom carousel

I'll even share my code with you!
Basically, I have a carousel that I built from the bottom up - Now, it works fine when there is more than one product being shown.
When there is only one product shown, then the animation jumps in IE (surprise...). Anyone have and idea how I could fix this up?
My jQuery for the sliding:
$(leftButton).click(function(){
var item_width = 205;
var left_indent = parseInt($('ul#carousel_ul').css('left')) + (item_width);
var $currElement = $('ul#carousel_ul li:last');
$($currElement).prependTo('ul#carousel_ul');
$('ul#carousel_ul').css({'left':-left_indent});
$('ul#carousel_ul:not(:animated)').animate({'left' : 0},carouselSpeed,function(){
$('#carousel_ul').css({'left':0}); //css fix
});
});
$(rightButton).click(function(){
var item_width = 205;
var position = $('ul#carousel_ul').position();
var left_indent = parseInt(position.left + item_width);
$('ul#carousel_ul:not(:animated)').animate({'left' : left_indent},carouselSpeed,function(){
var $currElement = $('ul#carousel_ul li:first');
if ($.browser.msie) {
$('ul#carousel_ul').css({'left':'11px'});
} else {
$('ul#carousel_ul').css({'left':'0px'});
}
$($currElement).hide().appendTo('ul#carousel_ul');
$($currElement).show();
});
return false;
});
And my HTML:
<div id="carousel_inner">
<ul id="carousel_ul">
<li name="1"></li>
<li name="2"></li>
<li name="3"></li>
<li name="4"></li>
<li name="5"></li>
<li name="6"></li>
<li name="7"></li>
<li name="8"></li>
<li name="9"></li>
</ul>
</div>
And finally, my CSS:
div#carousel_inner {
float:left;
width:205px;
height: 125px;
min-height: 115px;
margin-left: 25px;
position: relative;
overflow: hidden;
z-index: 75;
}
ul#carousel_ul {
position:relative;
left:0px;
list-style-type: none;
margin: 0 auto;
padding: 0px;
width:9999px; /* important */
height: 115px;
min-height: 115px;
bottom: 35px;
z-index: 75;
}
Try an absolute position like so:
ul#carousel_ul {
position:absolute;
left:0;
list-style-type: none;
margin: 0 auto;
padding: 0;
width:9999px; /* important */
height: 115px;
min-height: 115px;
bottom: 35px;
z-index: 75;
}
And where you wrote /* important */ did you not mean !important?? NOTE - Your carousal may now be positioned wrong, but at least test to see if it is FUNCTIONING properly with the above css...
Try replace this piece of code:
$('ul#carousel_ul:not(:animated)').animate({'left' : 0},carouselSpeed,function(){
$('#carousel_ul').css({'left':0}); //css fix
});
With this:
$('ul#carousel_ul').stop().animate({'left' : 0},carouselSpeed,function(){
$('#carousel_ul').css({'left':0}); //css fix
});
The code you've used to get the css left value here:
var left_indent = parseInt($('ul#carousel_ul').css('left')) + (item_width);
Will produce something like 100px and not 100, so you cannot add that to your item_width, because that would result in some math like 100px+300 which is incorrect. Try this:
var position = $('ul#carousel_ul').position();
var left_indent = parseInt(position.left + item_width);
position.left will return the left position of the object, while position.top will return the top position.
Reference: http://api.jquery.com/position/

Categories