Javascript going to the top of the page?

Asked

Viewed 104 times

0

Guys, I have a "Like" script only when I click on it the half page of a Reload and goes to the top. But when I do Load actually on the page, it goes to the place I clicked to give the "Like". What can this be?

Everything is working properly, the likes count part, add the likes in the database and everything.. What really happens is this "bug" that the page does not continue in the same place after I click on the "Like" button".

Script:

function add_like(post_id, hora_post){
    $.post("init/add_like.php", {id_post:post_id, post_data:hora_post}, function(dados){
       if(dados == 5){
           get_like(post_id, hora_post);
       } 
    });
}
function get_like(post_id, hora_post){
    $.post("init/get_like.php", {id_post: post_id, post_data:hora_post}, function(valor){
        $('#post_'+post_id+'_like').text(valor);
    });
}

Page add_like.php:

session_start();
include("../functions.php");
include("../conecta.php");
$post_id = $_POST['id_post'];
$hora_post = $_POST['post_data'];
if(!verificar_clicado($conecta, $post_id, $_SESSION['id'])){
    if(adicionar_like($conecta, $post_id, $_SESSION['id'], $hora_post)){
        echo 5; // Valor para ser enviado para o arquivo JS 
    } 
}

Page get_like.php:

session_start();
include("../functions.php");
include("../conecta.php");
$post_id = $_POST['id_post'];
$numero_de_likes = retornar_likes($conecta, $post_id);
echo $numero_de_likes;

Like Button:

 <a href='' name="id" onclick="javascript:
            var dado1 = '<?=$post['id']?>';
            var dado2 = '<?=$post['hora']?>';
            add_like(dado1,dado2);
            " class="like-post">Like</a>

Button that receives the likes:

<span id="post_<?=$post['id']?>_like">
                                <?php
                                    if($post['likes'] == 0){

                                    } else {
                                        echo $post['likes'];
                                    }
                                ?></span>

2 answers

3


Swap the anchor of the Like button for a span. href blank is causing a bearing to the top of the page.

0

If you want to continue using html anchor markup(<a href="#">...</a>) you can just use a return false; at the end of its function.

Example:

function add_like(post_id, hora_post){
    $.post("init/add_like.php", {id_post:post_id, post_data:hora_post}, function(dados){
       if(dados == 5){
           get_like(post_id, hora_post);
       } 
    });
    return false;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.