JQuery: Using .last() with a created element in a .on

110
January 26, 2018, at 09:47 AM

I'm currently making a tab structure similar to Google Chrome. I have recently made a "New Tab" button and function that adds a new tab. Right now my function only creates one tab. My code bases where the next tab elements will go in the HTML tree by using $(".tab-clickable").last().after(). The last .tab-clickable element represents the last part of the closest tab.

Here is my code: https://codepen.io/lectrician1/pen/baOxdO

I originally was using a .click event but switched to .on because I figured that there was an problem finding the the tab last created. So I ran a debugging test and apparently the .on wasn't the problem but the $(".tab-clickable").last().after() was. But remember, my code still creates a tab, only just one though. I think the issue has to deal with finding the last .tab-clickable element that was just created in the first tab made.

Answer 1

Main problem is you are checking tabAmount only on page load. Need to check it each time you want to add another to get updated count

Move :

var tabAmount = $(".tab-clickable").length;

Into

$("#button").on("click", function() {
   var tabAmount = $(".tab-clickable").length;
   // other code remains same
Answer 2

Please post the relevant part of your code in the question next time you ask, or edit your post.

You're determining the position of the new tab using the tabAmount variable which you initially set to 2. However, when you add a new tab, at no point do you increase this variable. Your code is producing new tabs, but they're just all being put in the same place over each other.

All you need to fix the problem is add tabAmount++ to the end of the function (and decrement it if you remove a tag, or take it from the length each time)

READ ALSO
What does the following Jquery code do?

What does the following Jquery code do?

I am learning basic Javascript and JqueryI was going through some codepen codes and was unable to figure out what the following jquery code does

112
How to change element colors with multiple JQuery MiniColors inputs? Rails 5

How to change element colors with multiple JQuery MiniColors inputs? Rails 5

How can I change the color of class elements that are targeted by multiple JQuery MiniColor Selector Inputs? The code that I have below is not rendering the correct resultsI simply need all inputs working separately on the components that they are targeting

160
Check for Cookie ; load() if cookie matches, need to reload to see new content

Check for Cookie ; load() if cookie matches, need to reload to see new content

Having issues with loading content based on Cookie value

103