Xeen
Xeen

Reputation: 7003

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.

Upvotes: 3

Views: 538

Answers (2)

fabian
fabian

Reputation: 82461

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();
    });

Upvotes: 2

talsibony
talsibony

Reputation: 8756

This will remove the last | char

function removeReverseCharLike(str,char){
    i = str.lastIndexOf(char);
    if (i != -1) {
        str = str.substr(0,i) + str.substr(i+1,i);
    }
    return str;
}

str = $('p:last').html();
removeReverseCharLike(str,char);

if you want to trim the last '|' char in case it is the last char in the sentence you will have to split the html string

strArr = $('#test').html().split('\n')
var html = '';
for(i in strArr){
  html += strArr[i].replace(/\|$/, '');
}

Upvotes: 0

Related Questions