Skip to content
Advertisement

PHP handling the addition of a class to an HTML element

I need to achieve the following: I have a php file responsible for sending my form. Everything works fine but I want php to add the class active to a div in my HTML so that a popup of message sent can be displayed on the page to the user. Here’s my html:

<div class="sentMessage">
    <i class="far fa-times-circle"></i>
    <p>Thank you! Your message has been successfully sent.</p>
</div>

this is my php script at the moment:

if ($sending) {
    // If the message is sent I output a string to use it  
    echo "SENDING"; 
}

what I want – instead of outputting the SENDING msg – is to add the class active so that my div looks like this:

<div class="sentMessage active">
    <i class="far fa-times-circle"></i>
    <p>Thank you! Your message has been successfully sent.</p>
</div>

Any help would be extremly appreciated! Thanks in advance.

Advertisement

Answer

Just make a condition in a div…

<div class="sentMessage <?php echo $sending ? 'active' : '' ?>">
    <i class="far fa-times-circle"></i>
    <p>Thank you! Your message has been successfully sent.</p>
</div>

We don’t know where $sending is defined, you should check if it exists first (isset, or !empty). Than it’d be

<div class="sentMessage <?php echo !empty($sending) ? 'active' : '' ?>">
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement