How do I stay on a webpage after event?

Hi
I’m a javascript newbie and am still trying to get around the logic.

I have adjusted a shopping cart tutorial to suit my needs for a “shortlist” instead of a “shopping cart”. It works well but after the item is added to the shortlist it redirects to the top of the original page. Because my “products” list is paginated this can be quite annoying so I need to write some javascript to tell the page to stay where it is after clicking the “add to shortlist” link.

This is the code on my products page to get information and add success message after event.

    <?php // to prevent undefined index notice
    $action = isset($_GET['action']) ? $_GET['action'] : "";
    $id = isset($_GET['id']) ? $_GET['id'] : "1";
    $name = isset($_GET['name']) ? $_GET['name'] : "";

if($action=='added'){
     echo "<div id='content'>";
    echo "<div class='alert alert-info'>";
    echo "<br><strong>{$name}</strong> was added to your Shortlist!";
     echo "</div>";
echo "</div>";

}

if($action=='exists'){
 echo "<div id='content'>";
   echo "<div class='alert alert-info'>";
    echo "<br><strong>{$name}</strong> already exists in your Shortlist!";
    echo "</div>";
 echo "</div>";

}
?>

This is my add to shortlist button.

    <a href="http://www.xxxxxx.com/shopping/add_to_cart.php?id=' . $id . '&name=' . $name . ' "<span class=btn>Add To Shortlist</span> </a>

I know I have to start my javascript like this:

<script type="text/javascript">
    jQuery(document).ready(function($){
    $('#button').on('click', function(e){
        e.preventDefault();          
      
</script>

And my button needs to look like this:

 <a id="button" href="#">Add to shortlist</a>

What do I need to do next?

Thanks

It looks like you have errors in your JavaScript, so that’s why it’s not working possibly…?

You have this:

<script type="text/javascript">
    jQuery(document).ready(function($){
    $('#button').on('click', function(e){
        e.preventDefault();          

</script>

But it should look like this:

<script type="text/javascript">
    jQuery(document).ready(function($){
      $('#button').on('click', function(e){
        e.preventDefault();
      }
    }
</script>

Which you could actually write shorter like this:

<script type="text/javascript">
    $(function () {
      $('#button').on('click', function (e) {
        e.preventDefault();
      }
    }
</script>

Unless you’re dealing with conflicts with another library, then you would need your version. But make sure to add the closing curly braces, which seemed to be missing from yours (unless you were just showing the abbreviated version or something?).

1 Like