Question

Here is my ajax code, i have 81 products per page...
When i click add to cart button a div appears on the center of the page but when i add product to last or bottom in page, div always appears on the center of page and i need to scroll up the page to see it.
I want the result where i am on page, like if i am bottom of the page, I want the div to appear on bottom .

    <script type="text/javascript" >
        $(function() {
           $('a.addbtn').click(function(e){
                 e.preventDefault(); 
                 var quantity = $(this).attr("qty");
                 var prod_id = $(this).attr("prid");
                 var dataString = '&quantity=' + quantity + '&prod_id=' + prod_id;
                 if(quantity=='' || prod_id==''){
                    alert('some thing went wrong');
                 }
                 else{
                   $.ajax({
                      type: "GET",
                      url: "ajax_checkout.php",
                      data: dataString,
                      cache: false,
                      success: function(html){
                           $('.addcart').remove('');
                           $("#viewr").append(html);
                      }
                   });
                 }
                 return false;
            }); 
        });
    </script>
Was it helpful?

Solution

Make the div viewr's position to fixed. like so:

    #viewr{    
        width:30em;
        height:18em;
        border: 1px solid #ccc;
        background-color: #f3f3f3;
        display:none;
    }

use whatever class you want to style it
Now add this function in the jquery, this will make the appear on the center of the screen:

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + 
                                                $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + 
                                                $(window).scrollLeft()) + "px");
    return this;
};

Now in your success function do the following to make it visible and invisible after some time:

success: function(html){
    $('#viewr').html(html);
    $('#viewr').fadeIn('slow').center().delay(2000).fadeOut('slow');
}

Do not use append(), that will always append the html in the div.
The delay amount is in milliseconds, so set it to whatever you require.
This should do the trick

OTHER TIPS

Whilst you can style this with jQuery and set an inline style with top I would always just use css and place it at the top of the browser. Although this means, until you close the box it will always be there, it won't be fixed where it opens.

 .addcart {
      position: fixed;
      top: 10px;
 }

Should do the trick

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top