JDesigns
JDesigns

Reputation: 2332

Control CSS border via jQuery

I am trying to add a border for a div but there are other divs inside it towards the end. I want to end the border until a particular div. Sample code is below. Will not be able to edit the actual template so I am looking for a jQuery/CSS solution to solve this. Adding border using specific CSS classes is an option but not a perfect solution as there is going to gap between sections and border will be missing.

$(".article-content")
  .css("border", "2px red solid")
  .find("#beforeFooter")
  .end();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="article-content">
  <div class="article-title">Title</div>
  <div class="article-share">Share tools</div>
  <p><span>Hello</span>, how are you?</p>
  <p><span>Hello</span>, your name?</p>
  <p><span>Hello</span>, your age?</p>
  <p>Ends here</p>
  <div id="beforeFooter"><img src="https://via.placeholder.com/600x150" /></div>
  <div class="article-footer">Some other footer content</div>
</div>

Upvotes: 0

Views: 43

Answers (1)

Brett DeWoody
Brett DeWoody

Reputation: 62743

One option is to get the offset of the #beforeFooter element (the number of pixels it's offset from the top of the .article-content element) then set the height of the .article-content to that offset.

var beforeFooterPosition = $("#beforeFooter").position();
$(".article-content").height(beforeFooterPosition.top);

Here's the working example. I had to subtract an additional 18 pixels for the border to be in the correct place. You'll want to experiment with that number to get the desired effect.

var beforeFooter = $("#beforeFooter").position();
$(".article-content").height(beforeFooter.top - 18);
.article-content {
  border: 2px solid red;
  overflow: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="article-content">
  <div class="article-title">Title</div>
  <div class="article-share">Share tools</div>
  <p><span>Hello</span>, how are you?</p>
  <p><span>Hello</span>, your name?</p>
  <p><span>Hello</span>, your age?</p>
  <p>Ends here</p>
  <div id="beforeFooter"><img src="https://via.placeholder.com/600x150" /></div>
  <div class="article-footer">Some other footer content</div>
</div>

Upvotes: 1

Related Questions