Reputation: 495
I have a list box, which when clicked, is removed and 'n' new list boxes of the same type are generated (n is input by the user on prompt when that list box is clicked). This process is repeatable.
But the width of the newly generated list boxes is not supposed to be the same as the original list box (the one that was clicked to generate new ones). If the original list box had a width of '200px' the newly generated items should have a width of '(200/n) px'.
Also I want the position (the target) of newly generated list boxes to be at the SAME place as the clicked one, i.e, not after the entire list (append) or not before the entire list (prepend) but just at the same place as that of the clicked list box, one after the other. (along with their widths reduced by n as mentioned above). Sorry I couldn't mention this in the title due to word limit.
I referred to other answers that recommended the use of After()
, InsertAfter()
etc, but I don't know how to implement them in my case as I am new to JavaScript and jQuery.
HTML:
<h4>Rhythm-Ruler</h4>
<div>
<ul class="list">
<li></li>
</ul>
</div>
JavaScript:
$("ul").delegate("li", "click", function(){
var inputNum = prompt("Divide By:");
// 'n' input by user and stored
if(inputNum>1){
$(this).remove();
}
var i;
for (i=1;i<=inputNum;i++){
var newList=document.createElement("li");
$(".list").append($(newList).text(i));
//this is making them assemble 'after' the entire list
$(this).css('width', 200/inputNum + 'px');
//I am dividing the width by n but its not working
}
});
CSS:
li {
/*position: fixed;*/
float: left;
list-style: none;
width: 200px;
height: 30px;
box-shadow:0 -1px 1em hsl(60, 60%, 84%) inset;
background-color: #FF7F50;
display: inline;
text-align: center;
padding: 2px;
}
JSFiddle: https://jsfiddle.net/yoshi2095/gwpf42ds/6/
Upvotes: 3
Views: 278
Reputation: 6785
Updated fiddle with working example.
https://jsfiddle.net/z90hg3z5/
$("ul").delegate("li", "click", function()
{
var inputNum = prompt("Divide By:");
if(inputNum>1){
var i;
var w = $(this).width();
$(this).remove();
var newW = w/inputNum;
}
else
{
newW = w;
}
for (i=1;i<=inputNum;i++)
{
var newList=document.createElement("li");
$(".list").append($(newList).text(i));
$(newList).css('width', newW);
}
});
Explanation. You need to get the width of the clicked element, so that you can do the math, divide it by the input number. Then remove the original element.
Updated code to insert new element at the correct place.
$("ul").delegate("li", "click", function()
{
var inputNum = prompt("Divide By:");
if(inputNum>1)
{
var i;
var w = $(this).width();
var newW = w/inputNum;
}
else
{
newW = w;
}
for (i=1;i<=inputNum;i++)
{
var newList=document.createElement("li");
$(newList).text(i).css('width', newW).insertAfter($(this));
}
});
Edited code formatting
Upvotes: 2