Rajan Sinha
Rajan Sinha

Reputation: 17

Automatically Scroll to a particular PHP message after click of a button

In my website (Talklast.com) there's a contact page, and when users fill in the contact form and click on send a message using PHP is displayed which is done using echo.

So, I am trying to get users automatically scrolled to the message after the "Send" button is clicked, In other words, I want to users to be automatically scrolled to a particular text after the click of a button (also, when the button is clicked, the page is reloaded).

I was checking the below code I found in stack overflow, but it is not helping in my case -

$(document).ready(function () {
    // Handler for .ready() called.
    $('html, body').animate({
        scrollTop: $('#what').offset().top
    }, 'slow');
});

This is the PHP message I referred earlier (to which user should automatically scrolled to after the click of "Send" button -

<span style="color:green;"><?php if(isset($smsg)){ echo $smsg;}?></span>

Upvotes: 1

Views: 1546

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115242

Set some selector to the button for uniquely identifying ( id or class ), then bind click event handler and do the rest within the handler. To scroll to the span give an id to the span element and use that to scroll.

JQuery :

$(document).ready(function () {
  // attached click event handler
  $('#button').click(function(){
    $('html, body').animate({
        scrollTop: $('#span').offset().top
    }, 'slow');
  });
});

Span:

<span id="span" style="color:green;"><?php if(isset($smsg)){ echo $smsg;}?></span>
<!-- -^^^^^---- id --->

Button :

<button type="submit" name="send" id="button" class="btn btn-primary btn-lg" style="padding: 3px 16px;" title="Click to send your message to Talklast.com">Send</button>


UPDATE : Set your form action as follows to scroll to the span when reloading.

<form action="#span" method="POST">

Ref : https://support.google.com/richmedia/answer/190941?hl=en

Upvotes: 1

Related Questions