Ali
Ali

Reputation: 9

Shorten clickable titles in responsive design using jQuery substring and media queries

I have a div with title

<div class='titles'>
<h2 class="post-title"><a href="www.example.com">Some example Title 1</a></h3>
<h2 class="post-title"><a href="www.example.com">Some example Title 2</a></h3>
<h2 class="post-title"><a href="www.example.com">Some example Title 3</a></h3>
</div>

I want these title to become shorten automatically with certain limit of text when view in mobile devices i.e. responsive.

For example, the title becomes

some example...

Moreover, they should be clickable according to their link.

Basically, I want to automatically shorten the titles length with jquery in responsive media queries.

I found the follwoing script and tried

$(window).resize(function() {
    if (window.matchMedia('(max-width: 600px)').matches) {
      
       $("h3.post-title").each(function(){
    len=$(this).text().length;
      $(this).text($(this).text().substr(0,20)+'...');

  });       
      
 
    }
});

But it shorten the text which is not clickable according to the url of title and it does not produce the full title when the max-width is not 600px.

**I want the clickable title with certain length and which trigger only when width is 600px or less otherwise full title. ** Thanks

Upvotes: 0

Views: 26

Answers (1)

Bridging Shores
Bridging Shores

Reputation: 21

Working fiddle: https://jsfiddle.net/4g91evsb/34/. One issue is your html, you have a mix of h2 and h3 tags.

<h2 class="post-title"><a href="www.example.com">Some example Title 1</a></h3>

I've corrected it in the attached fiddle.

I've also included some suggestions for your jquery. I set the character limit to 10 to make the change easier to test.

In my example I just stored the original value into the data field of the <a> tag (see data-original=""). You might choose to store these in some other variables. The reason it wasn't changing back was because you were overwriting the original text value so you could never return to it. That's why you need to store a copy of it. If you have any questions about my answer, let me know in a comment.

Upvotes: 0

Related Questions