soum soum - 1 year ago 41
jQuery Question

add a list element after clicking a anchor tag at a desired position

I am trying to add a

after i click an anchor tag (quick view, which shows when you hover over the gray boxes). The logic is if the the element is am clicking is at at a position which is a multiple of 3 then I adding the
right after that, which works fine. The problem is when I have a remainder of 1 and 2. It is moving the
right next it. If the description doesn't make sense please let me know and I can try to explain it more. Here is the algorithm

if r = 0
do (add an element at this + 1);
if r <= 1
do (add an element at this +3);
if r = 2
do (add an element at this + 2);

Where r is the remainder, r = p/3 ..p is the position of the element

Here is the JS

$('.quick-view').on('click', function(e) {
var productIndex = $(this).parent().attr('data-loopcount');
var r = productIndex % 3;
var index = $(this).parent().index();
if(r == 0){
$('<li class="product-drawer">'+Number(index + 1) +'</li>').insertAfter($(this).parent());
}else if(r == 2){
$('<li class="product-drawer">'+Number(index + 2) +'</li>').insertAfter($(this).parent()).eq(Number(index + 2));
}else if(r <= 1){
$('<li class="product-drawer">'+Number(index + 3) +'</li>').insertAfter($(this).parent()).eq(Number(index + 3));

here is the jsfiddle

Answer Source

The error is in the call to .eq(): that only makes sense if you apply it to a jQuery object that has multiple matches. But $(this).parent() will only return one element, so applying eq() to that makes no sense.

Instead, make use of .next().

Here is a solution based on that, which also minimises a bit the code to avoid repetition:

$('.quick-view').on('click', function(e) {
    var $curr = $(this).parent();
    var productIndex = $curr.attr('data-loopcount');
    var r = productIndex % 3;
    var index = $(this).parent().index() + [1, 3, 2][r];
    var $li = $('<li class="product-drawer">' + index +'</li>');
    var $target = [$curr, $, $][r];

See the updated fiddle.

Further work might be necessary, depending on what you are after. For instance, the newly inserted li elements, may need to get some other attributes. Also, the selection based on data-loopcount is a bit obscure. Without further context it is hard to imagine what purpose it has.