Xeen Xeen - 4 months ago 17
Javascript Question

How to detect the last element in a line with jQuery?

I have this markup here:

<p>
<?= $d['contact'] ?> | <?= $d['address'] ?>
</p>
<p>
T: <?= $d['phone'] ?> |
<a href="mailto:<?= $d['email'] ?>"><?= $d['email'] ?></a> |
<a href="http://<?= $d['website'] ?>" target="_blank"><?= $d['website'] ?></a>
</p>


And since it's for a responsive layout, I'd like to remove the
|
seperator when it's the last element on a line. Is that possible? I'm thinking of wrapping it in
<span></span>
and call it out whenever it's the last element.

Answer

It can be done, if you make sure the content following the seperator a element and then check the positions of the seperator and the next element:

<p>
    <?= $d['contact'] ?><span class="seperator"> | </span><span><?= $d['address'] ?></span>
</p>
<p>
    T: <?= $d['phone'] ?><span class="seperator"> | </span>
    <a href="mailto:<?= $d['email'] ?>"><?= $d['email'] ?></a><span class="seperator"> | </span>
    <a href="http://<?= $d['website'] ?>" target="_blank"><?= $d['website'] ?></a>
</p>
$(function () {
    $(window).resize(function () {
        $(".seperator").each(function () {
            var t = $(this);
            // use visibility since it does not free the space
            t.css("visibility", (t.next().offset().top > t.offset().top) ? "hidden" : "visible");
        });
    }).resize();
});

Edit: t.next().offset() must be checked for .length, otherwise console will show error for last element Uncaught TypeError: Cannot read property 'top' of undefined (there is no .next() after the last element). So code should be something like:

$(function () {
        $(window).resize(function () {
            $(".seperator").each(function () {
                var t = $(this);
                var this_offset = t.offset().top;
                if (t.next().length) {
                  var next_offset = t.next().offset().top; 
                }
                // use visibility since it does not free the space
                t.css("visibility", (next_offset > this_offset) ? "hidden" : "visible");
            });
        }).resize();
    });
Comments