Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a read more link after image while grabbing the page title URL with jQuery

I have a jSfiddle file here.

I want to add a read more link after the image or after certain character limit maybe around 100. But i'm having issues grabbing the link of the page title. I want to make the script dynamic.

Right now my jQuery is written like this.

jQuery

$('.BlockContent p').each(function() {
    var txt = $(this).text();
    var link = $('#NewsContent .p-name').attr("href");
    if (txt.length>5) {
        $(this).html('<span>'+txt.substring(0,5)+'&nbsp;&nbsp;</span><a href="link"> Read More</a>');
    }
}); 

My HTML

<div class="BlockContent" id="NewsContent">
    <img src="http://placehold.it/600x300">
    <h1 class="p-name"><a href="#">Page Title</a></h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam in odio mi. Fusce varius urna quis sem viverra id laoreet sem imperdiet. Morbi ultricies varius tortor, in congue ipsum facilisis ut. Suspendisse potenti. Nam ut eros quis orci eleifend rutrum vestibulum adipiscing nisl. Morbi mauris dui, iaculis consequat auctor in, auctor vel velit. Mauris lacinia adipiscing sapien, vel mollis massa pulvinar et. Curabitur eu urna venenatis nisi rhoncus eleifend. Nam dapibus lectus ac libero aliquet id malesuada tortor accumsan. Mauris lacus orci, euismod ac vehicula nec, scelerisque non tortor. Praesent quis odio a elit congue luctus. Aliquam ultricies, massa quis gravida tincidunt, justo mi scelerisque lectus, fringilla hendrerit tortor metus quis tellus. Suspendisse sit amet felis eu erat mollis rhoncus at non ligula. Fusce odio est, consectetur sed scelerisque quis, rhoncus ac lectus. Donec accumsan viverra eros, et vulputate augue laoreet et.</p>
</div>

Can someone point out what i am doing wrong?

like image 612
breezy Avatar asked Jan 24 '26 04:01

breezy


1 Answers

Your code to grab the title link is selecting the h1 element instead of the anchor within it.

Change: var link = $('#NewsContent .p-name').attr("href");

to: var link = $('#NewsContent .p-name a').attr("href");

Then you need to properly concatenate that variable in your string:

$(this).html('<span>' + txt.substring(0, 5) + '&nbsp;&nbsp;</span><a href="'+link+'"> Read More</a>');

jsFiddle example

like image 93
j08691 Avatar answered Jan 25 '26 16:01

j08691