How to insert an element at the middle of a post using #jQuery?


There could be some possible business cases where we need to insert a HTML element inside a post. This should not be a static one but a dynamically injected at the middle of the article. So, what to do in such case? How can we insert it by writing some code?

 

Today in this blog post, we are going to see the same with the help of jQuery code. This will not only reduce the burden of writing huge code, but also give a better performance.

 

jQuery to insert element at the middle of a post (www.kunal-chowdhury.com)

 

If you are building a webpage and have any business need to dynamically insert a HTML content or ads block, you can use jQuery script to perform the same easily without any hassle. Before implementation of the code, you first need to understand the case of the logic as mentioned below:

    • The requirement is not to randomly insert at the middle of the page. This is because, it may insert the element at the middle of a line and/or within an existing element.
    • Requirement is to insert the content only when the paragraph (<p> tag) ends and/or have a line break (<br> or <br/>).

For this, we need to find out all the tags having 'p' and/or 'br'. Then we have to get the content length of the same and find out the mid of the content where 'p' and/or 'br' exists. And then after the end tag of the said element, insert the content/element that you want to dynamically place.

 

Here's the code for your reference:

 
<script>
$(document).ready(function() {
    var content = $('.content').find('p, br');   // '.content' is the class of the panel
    var midLength = parseInt(content.length/2);
    content.eq(midLength).after("<p>Your content here</p>");
});
</script>

 

If you came to this page searching on this topic, I hope, this solved your problem. Drop a line below with your comments. If you have any other approach to share with the other developers, also post your solution in the comments section.

 

 


If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Twitter, Facebook, Google+ and LinkedIn. I would love to hear your thoughts and opinions on my articles directly. Also, don't forget to share your views and/or feedback in the comment section below.

0 comments

 
© 2008-2016 Kunal-Chowdhury.com - Microsoft Technology Blog for developers and consumers | Designed by Kunal Chowdhury
Back to top