0

I created a code following the link example: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_overlay_text

The problem that opens only the first post on all buttons. How do I solve this?

My code:

<style>
#overlay {
    position: fixed;
    display: none;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0,0,0,0.5);
    z-index: 2;
    cursor: pointer;
}

#text{
    position: absolute;
    top: 50%;
    left: 50%;
    font-size: 12px;
    color: white;
    transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
}
</style>
<?php /* Template Name: Equipe  */ ?>

<?php get_header(); ?>

<?php
$args = array( 
    'post_type' => 'cpt_profissionais',
    'post_status' => 'publish',
    'order' => 'ASC',
    'posts_per_page' => 9999,
    'paged' => $paged );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post(); ?>

<?php the_title(); ?>

<div style="padding:20px">
  <button onclick="on()">Clique e saiba mais</button>
</div>

<div id="overlay" onclick="off()">
  <div id="text"> <?php the_content(); ?></div>
</div>  

<?php endwhile; ?>

<?php get_footer(); ?>

<script>
function on() {
    document.getElementById("overlay").style.display = "block";
}

function off() {
    document.getElementById("overlay").style.display = "none";
}
</script>
2
  • 1
    you are using the same CSS id on all posts; it would need to be a specific CSS id per post with its specific CSS id referred to in the script
    – Michael
    Commented Apr 1, 2018 at 23:16
  • @Michael I figured it was this problem, how do I solve it? Any suggestion?
    – J.Z
    Commented Apr 2, 2018 at 3:20

1 Answer 1

1

to be able to identify a specific "post" you need to have some unique attribute in its HTML. Usually the easiest thing to do is to use the post id as part of the id attribute (in your case maybe something like overlay{$post_id}). I personally started to prefer to use data- style attributes instead but for this use case the difference is more of esthetics than anything else.

Now that you have everything unique (and maybe even instead of doing that at all), either use a common class on all the "posts" and have a handler for click on elements with that class (easy with jQuery), or add a click handler on the containing div instead of the elements, and in the handler look at the event properties to find out which "post" was actually clicked.

Not the answer you're looking for? Browse other questions tagged or ask your own question.