I have HTML code for kind of blog page. Below - code of 1 post and its height cuts by CSS. It will be many posts on blog page. I want to see all content of particular page by clicking "Read More" button. Div with blog content has dynamic id which gets from database by PHP.
How can I change height of div with class "blog_article" by clicking "Read More" button?
I thought of using JS/Jquery but cannot get id of "blog_article" div. Or maybe there is some better way to do this?
<div class="blog_article_wrapper">
<div class="blog_article" id="<?php echo $id; ?>">
<!--Some content-->
</div>
<div class="blog_article_read_more">
<button onclick="blogReadMore()">Read More</button>
</div>
</div>
but cannot get id of "blog_article" div
Why can't you?:
<button onclick="blogReadMore(<?php echo $id; ?>)">Read More</button>
Or, if it's a string:
<button onclick="blogReadMore('<?php echo $id; ?>')">Read More</button>
Then blogReadMore()
has a reference to the id
:
function blogReadMore(id) {
// use the id to identify the element and modify it however you want
}
Conversely, since you tagged jQuery, you can traverse the DOM from the button click to determine the element without needing any id
at all. Something like this:
$('.blog_article_read_more button').click(function () {
var article = $(this).closest('.blog_article_wrapper').find('.blog_article');
// do whatever you like with the article
});
There's a more straight forward way than Azim's answer, but based on the same ideas:
I would still use the read_more
class, although not actually needed. I will assume such a class applied to the button.
$('.read_more').click(function(){
var blog_article = $(this).parent().parent().find('.blog_article');
blog_article.css('height', '100px'); //change height here
});
In this case I use .parent()
method in order to get the parent object from the clicked item, rather than relying on .closest()
. Two calls to .parent()
are needed because the <button>
resides inside a <div>
and we need the parent of that div before we can drill down.
Alternatively:
$('.read_more').click(function(){
var blog_article = $(this).parent().prev();
blog_article.css('height', '100px'); //change height here
});
Because the button's parent <div>
is the direct sibling of the one we're interested in. No selectors needed at all!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With