Javascript/Jquery element carousel - javascript

I am trying to make a javascript/jquery carousel. I have an unordered list and inside the ulist i have more lists. I get the first lit with:
list = $(wrapper).find("li:eq(0)").show()
On the button-next down i want it to show next list so it would be:
list = $(wrapper).find("li:eq(1)").show()
on the button-previous i want the list to show previous list. How could I achieve something like this, to append ("li:eg(x+1/x-1)).show()

Introduce a variable to keep track of the current list. When a user clicks the next button, increment it by one, and vice-versa for when previous is clicked. Then use this variable in your selector.
list = $(wrapper).find("li:eq("+ currentList +")").show()
Sidenote: You might want to introduce some bounds checking so currentList never goes below 0 and never exceeds the number of lists you have available.
//On previous click
if(currentList - 1 > 0){
//do something
}
//assign a variable to keep track of the upper bounds
var maxList = $(wrapper).find('li').length;
//On next click
if(currentList + 1 < maxList - 1){
//do something
}

Related

Keeping track of items added to a page on button click

I have a for loop inside a button for an image gallery. When you click the button it will get the next group of items and add them to the page until there are no items left to grab. I was originally keeping track of the position in the array by adding the amount of items that should be added with each click to the previous value on each click. I wanted to change these vars to const, but if const in ES6 is not supposed to change (stay constant) how do you achieve this same result by not changing the value of the variables? Are my methods of keeping track of the current count of items not how I should be doing this?
var itemCurrent = 10; // Starting number of items on page.
var itemsAdded = 15; // Number of items to add to page per button click.
document.getElementById('myButton').addEventListener('click', function() {
for (let i = itemCurrent; i < itemCurrent + itemsAdded; i++) {
if(i < data.projects.length) {
//Do Stuff---------------------
}
}
itemCurrent = itemCurrent + itemsAdded;
});
I thought maybe there would be a more elegant way to do what I wanted, but it seems using let instead of var and leaving everything the way it was is the best way.

How to edit the ID of each button in a class if a condition is true in JavaScript?

I'm using ChartJS to generate a pie chart in that elements are added every time the user clicks a specific button (I have 14 buttons that trigger the adding of a specific element in the pie chart, each one triggers a function that adds info to 3 arrays as needed in order for the chart to work.
Every time the user clicks a button a new one is created in a div that contains all the elements that are present in the chart because I want them to be able edit or delete the elements as needed.
To know what which elements from my arrays is edited by which edit button I'm using a variable named btnctr that I initialized with 0 at the beginning of my JS file. That variable gives every new ”edit button” an ID and then then increments, like this:
function CreateEditButton() {
var buttonnode= document.createElement('input');
buttonnode.setAttribute('type','button');
buttonnode.setAttribute('id',btnctr);
...
$("#rotationelements").append(buttonnode);
$("#rotationelements").append(' ');
btnctr++;
};
My problem is that I also have to make deleting elements possible. I'm using splice for deleting elements from the arrays, but that also messes up the position of other elements and my edit buttons become useless.
I want to also edit the IDs of my buttons when I delete elements, because I need them to be in sync.
Here's what I've come with so far:
// Get editbuttons
var editbuttons = document.getElementsByClassName('editbtn');
// Delete element
function deleteElement (x) {
names.splice(x,1);
dataset.splice(x,1);
colors.splice(x,1);
chart1.update();
time=time-length[x];
length.splice(x,1);
UpdateTime();
var delbtn=$("#"+x);
$(delbtn).remove();
var newid=x;
for (var i=0; i<editbuttons.length;i++) {
if (editbuttons[i].id>x) {
editbuttons[i].id=newid;
newid++;
btnctr=newid++;
}
}
}
Thanks!
Lulian, inside of your for loop it looks like you are only changing the id's of editbtns after the one that was deleted above. You may want to try taking out the if statement and replacing "newid" with "i":
for (var i=0; i<editbuttons.length;i++) {
// if (editbuttons[i].id>x) {
editbuttons[i].id=i;
//newid++;
btnctr=i;
// }
}
This way you can re-initialize all of you editbtn's and btnctr to match from beginning to end.

Odd behavior when removing action buttons from a table in JavaScript

I have a page that builds a table using DataTables, and each row has an Action Button that adds some data (an ID, just an int) from that row to a list. To keep users from clicking each action button multiple times, I made it so a row's button is removed the first time you click it. This worked great until I realized the buttons come back if you switch to the next page of the table and then switch back to the first page.
To fix this, I wrote some JS to compare each row to my list of data, and if that row's data is already in the list, it removes that row's action button. This happens each time the table is reloaded (for example, when you switch to a different page of the table and back again) using DataTable's draw.dt function.
The problem is, when I switch pages and the JavaScript goes to work removing buttons, for some reason it skips every other row. For example, if I click (thus removing) the first three rows' action buttons, switch pages and switch back, my JS removes the action buttons on row 1, 3, and 5 instead of rows 1, 2, and 3. It's so consistent that it has to be some kind of simple looping error due to my sloppy JS skills, but I can't find it.
Here is the code:
$(document).on('draw.dt', function () {
var $allSerialNumbers = $('.box-electrode'); // This is a list of all the rows' action buttons / ID's
$('#electrodes li').each(function (i, li) { // This is the list of ID's I'm comparing to
var $id = $(li).data('id');
for(var index = 0; index < $allSerialNumbers.length; index++){
if($id == $allSerialNumbers.eq(index).attr('data-id')){ // For each item in my ID list, run through all the rows and see if any Action Button ID's match any on the list
$('.box-electrode').eq(index).remove(); // If they do match, remove that Action Button
}
}
})
});
I'm not an expert on JQuery, but could remove() in your last line be re-sizing the list so that the element which used to be at index 1 is now at index 0, causing you to skip it when you increment the index?

Fundamentally doing something wrong with function calls. Functions do work in the console

This is a solid, proper syntax set of functions, and for the life of me I can't figure out why, but the function ServiceHover() will not run unless I trigger it manually in the console, while it's almost exact equal CategoryHover() runs perfectly each time. It has to be something about the way that I'm calling the functions, and clearly there's something about functions that I fundamentally missed in javascript, because this happens to me often, where I'm unsure why my functions are not executing.
I keep my code all very well commented, so I shouldn't have to explain the functions's purposes, and furthermore, this is more a question of the fundamental execution of the functions rather than their inner functionality. Each function does work if called manually in the console.
//this function generates the content of the page based on which category the user selects,
//which services the user selects, and help maneuver through each stage of the feature selection
//so that the QuoteEngine function can display the user's selected hour count, price per hour
// and total cost of the needed service so that the user can see very clearly what services
//he is getting and where every dollar of his total cost is coming from so that the user can
//make a well informed purchase decision, and be able to clearly understand the services offered
//and related pricing.
$(document).ready(function () {
function BasicDropdown() {
//hide the drop-downs to begin with
//hide element with class dropdown-category
$(".dropdown-category").hide();
//hide element with class dropdown-service
$(".dropdown-service").hide();
//when the category list title is hovered over, show the category drop-down list
//when element with class category is hovered, do this:
$(".category").hover(function () {
//show the list
$(".dropdown-category").show();
//when element with class category is no longer hovered, do this:
}, function () {
//hide the list
$(".dropdown-category").hide();
});
//when the service list title is hovered over, show the service drop-down list
//when element with class service is hovered, do this:
$(".service").hover(function () {
//show the list
$(".dropdown-service").show();
//when element with class service is no longer hovered, do this:
}, function () {
//hide the list
$(".dropdown-service").hide();
});
}
//change the selected service based on an id input
//create a function to change the selected service
function ChangeService(id) {
//clear the service list element
$(".dropdown-service").empty();
//make the name inside the service drop-down title show the new title
$("#ServiceOutput").text(ServiceArray[id][0][1]);
//loop through the chosen section of the service array for as many times as the
//section is in length
for (var i = 0; i < ServiceArray[id].length; i++) {
//each loop, append a paragraph element with a data key equal to the current
//loop count, an id equal to the id of the array area based on the loop count,
//and also insert the element's text according to that loop count also.
$(".dropdown-service").append('<p data-key="' + i + '" id="' + ServiceArray[id][i][0] + '">' + ServiceArray[id][i][1] + "</p>");
}
//set the variable "Category" to be equal to the chosen id.
Category = id;
}
function CategoryHover() {
//make the category drop-down list open and show its list of services
//when the user hovers over an element in the category drop-down, do this:
$(".dropdown-category > p").hover(function () {
//hide the welcome wrapper
$(".welcomeWrapper").hide();
//set the variable "thisKey" based on the value of the data "key" attached
thisKey = $(this).data("key");
//create a variable "outputList" and assign a value to it from "CategoryArray"
outputList = CategoryArray[thisKey];
//set the title of the category drop-down lists title to the currently hovered text
$("#CategoryOutput").text($(this).text());
//call the ChangeService function and pass the variable "thisKey" into it
ChangeService(thisKey);
//show the service drop-down list
$(".dropdown-service").show();
//show the ListOutput element (this shows a short description of the hovered element)
$(".ListOutput").show();
//append the variable "outputList" as the value of a paragraph element
$(".ListOutput").append('<p>' + outputList + '</p>');
}, function () {
//hide the service drop-down list
$(".dropdown-service").hide();
//empty the ListOutput element
$(".ListOutput").empty();
//hide the ListOutput element
$(".ListOutput").hide();
//show the welcome wrapper again
$(".welcomeWrapper").show();
});
}
function ServiceHover() {
//make the service drop-down list open and show the list of services for the category
//when the user hovers over an element in the service drop-down, do this:
$(".dropdown-service > p").hover(function () {
//hide the welcome wrapper
$(".welcomeWrapper").hide();
//set the variable "thisKey" based on the value of the data "key" attached
thisKey = $(this).data("key");
//create a variable "outputList" and assign a value to it from "CategoryArray"
outputList = ServiceArray[Category][thisKey][2][0];
//show the ListOutput element (this shows a short description of the hovered element)
$(".ListOutput").show();
//append the variable "outputList" as the value of a paragraph element
$(".ListOutput").append('<p class="blue">' + outputList + '</p>');
}, function () {
//empty the ListOutput element
$(".ListOutput").empty();
//hide the ListOutput element
$(".ListOutput").hide();
//show the welcome wrapper again
$(".welcomeWrapper").show();
});
}
BasicDropdown();
CategoryHover();
ServiceHover();
//initiate
ChangeService(0);
});
What am I doing wrong with these calls?
JS Fiddle: http://jsfiddle.net/gbJcg/4/
Note: I mentioned in my question but for some reason the update didn't show up, that all of the arrays should be assumed defined. I'll now include them to remove confusion, but it will make the scripts extensively long
Added detail: ChangeCategory works. ChangeService doesn't appear to. If I copy and paste ChangeService, however, in the console, and call it, in the console, the functionality works perfectly. Does that help? I have no idea what I'm doing wrong here...
Well what I know is, since your dropdown-service is added dynamically, you need to delegated it to closest static parent present in the document which is dropdown-service in your case.
$(".dropdown-service").on("mouseenter" ,"p",function () {
..
});
$(".dropdown-service").on("mouseleave" ,"p",function () {
...
});
Since live is deprecated in latest version of jQuery you need to use on delegated event and break the hover into mouseenter and mouseleave function.
fiddle here
Check your console, you have Uncaught ReferenceError: ServiceArray is not defined
This Exception is thrown and the rest of the program is not ran
EDIT: after fiddle changed with the missing Arrays initialization is seems like the code works. I added alerts in the begining of 2 functions to make sure they are called (see http://jsfiddle.net/gbJcg/3/)
EDIT #2:
The call to $(".dropdown-service > p").hover(...) is done when you do not have any elements that respond to ".dropdown-service > p" selector, They are probably added later via ajax or some other html manipulation that is done by js
You should use the equivalent for jquery live instead:
$(document).on("mouseenter",".dropdown-service > p",function() {
....
});
$(document).on("mouseleave",".dropdown-service > p",function() {
....
});

Jquery Disabling individual buttons within search results that all have the same classes applied

If you take a look at: http://www.thebullionstore.co.uk/_shop/?_cat=9
You will see a list of products each wrapped in a div with the class product_box. Inside product_box there several other divs and a form with an add to cart button. inside the form there is a hidden input field called stock_amount with a value, the value attribute is the amount of each product that is in stock. Iv also added a number base to the stock_amount class name to distinguish each product listing such as stock_amount0, stock_amount1 ans so on.
I want to be able to disable each button for each individual product after a certain amount of clicks. The amount of clicks will be equal to the value of stock_amount so in-effect a user cant add more products to the cart than is available.
Adding to the cart is currently done with Jquery but I don't know jquery well enough to figure out how to loop through each product listing and do what I described above.
Any help would be much appreciated.
$("button.addtocart").click(function(e) {
// fetch <input name='stock_amount'> within the clicked buttons form element
var stock_amount_input = $("input[name='stock_amount']", $(this).parent());
// fetch <input name='_qty'> within the clicked buttons form element
var qty_input = $("input[name='_qty']", $(this).parent());
// maybe you want to do some check here
var new_amount = stock_amount_input.val() - qty_input.val();
// set the new calculated value in the stock_amount input
stock_amount_input.val(new_amount);
// if the new_amount is less than 1 we dissable the clicked button
if(new_amount < 1) {
$(this).attr("disabled", "disabled");
}
});
To loop thorough elements you can use the jQuery.each(). Or write something like this:
var nodes = $("form");
for(var i=0; i<nodes.length; i++) {
var node = nodes[i];
// do something
}
But I don't think you need to do this. You can preform the check and the disabling of the button in the click-event-handler. Furthermore you shouldn't forget to check if the entered amount (e.g. 1000) doesn't exceed the stock amount.

Categories

Resources