2

This is the continuation of this question: jquery: how to detect element that is being loaded every few seconds

turns out my code from the link above ^ works fine. I don't know why it didn't work at first.

Now instead of alerting on click..

I am trying to scroll to an element from the attribute href.

<a href="#scrolltothiselement" class="gotobtn">click</a>
...
<div id="scrolltothiselement"></div>
...

This is how i am doing it:

$(document).on('click', '.gotobtn', function() {

  var gotothisid = $(this).attr('href');
  $(document).find(gotothisid).focus();

  return false;
});

I also tried:

$(document).unbind().on('click', '.gotobtn', function(event) {
  event.preventDefault();
  var gotothisid = $(this).attr('href');
  $(document).find(gotothisid).focus();
});

It's not working :'(

NOTE: The

<a href="#scrolltothiselement" class="gotobtn">click</a>
...
<div id="scrolltothiselement"></div>
...

is loaded into index.html like

setInterval(
function ()
{
$('.loadHere').unload().load('filetoload.php').fadeIn('slow');

}, 10500);

I already explained it in the link above :p

FURTHER DETAILS: This isn't everything but I think there's a good chance the problem is somewhere within the code i have shown below. I have also changed the variable names and class names. I'm sorry i can not show everything because it is confidential.

index.php

<?php include_once 'header.php'; ?>
<input type="hidden" class="currentlyvisibletab" value="" />


<div class="AllDateTimeTabs">


    <div id="today" class="datetimetab today-cont">
        <?php include_once 'today.php'; ?>
    </div>

    <div id="tomorrow" class="datetimetab tomorrow-cont">
        <?php include_once 'tomorrow.php'; ?>
    </div>

    <div id="yesterday" class="datetimetab yesterday-cont">
        <?php include_once 'yesterday.php'; ?>
    </div>


</div>
<div id="testscrollhere">Scroll here. animate code works here.</div>

<?php include_once 'footer.php'; ?>

today.php , tomorrow.php , yesterday.php has similar structure just different queries.

<?php

include_once 'connect.php';

$thisfiledate = date('Y-m-d');



$result = $conn->prepare("SELECT * FROM tbname WHERE field= :thisfiledate AND anotherfield= 'value';");
$result  -> bindParam(':thisfiledate', $thisfiledate);
$result->execute();


$displaydate = 'Today '.$thisfiledate;
include 'maincontent.php';


?>

maincontent.php - i'll erase some parts because they are confidential. but you get the point. maincontent.php has while loop which displays the stuff that were selected from the table. Each row from the table has its own

<div id="'.$row['rownumber'].'">details goes here</div>

There's a winner button on the top and if you click on it, it will scroll to the row which is the winner. There is only one winner. The winner button is

`<a href="#123" class="gotobtn">123</a>`

as discussed.

<?php

...

while ($row = $result->fetch(PDO::FETCH_ASSOC))
{


    ...



     $displayall  .= '<div class="col-md-1 col-sm-2 col-xs-4 c-cont-col">';
        $displayall  .= '<div class="c-cont '.$cyellow .'" id="'.$row['rownumber'].'">';
            $displayall  .= '<h4 class="winnerlabel '.$wiinerlavelinvisibility .'">WINNER</h4>';
            $displayall  .= '<h4 class="cn-label '.$labelcolor.'">'. $row['rownumber']. '</h4>';
            $displayall  .='<div class="ci-cont">';
            //$displayall  .= '<p><b>Date:</b> '.$row['cut_off_date_tmstrans'].'</p>';
            $displayall  .= '<p><b>label:</b><br>'.number_format($row['x'],2).'</p>';
            $displayall  .= '<p><b>label2: </b><br>'.number_format($row['y'],2).'</p>';
            $displayall  .= '<p><b>label3: </b><br>'.number_format($row['z'],2).'</p>';
            $displayall  .= '</div>';
        $displayall  .= '</div>';
    $displayall  .= '</div>';


}

if($haswinner == 0)
{
    $winnerboxinvisibility = 'invisibility';
}
else
{
    $winnerboxinvisibility = '';
}

echo '<div class="row">';
echo '<div class="col-md-6 col-sm-4 col-xs-12 date-cont-col">     <div class="pull-left date-cont">'.$displaydate.'  <div class="zerocountercolordot"></div> '. $zerocounter.'  <div class="lessorequaltotencolordot"></div> '.$lessorequaltotencounter.'  <div class="lessorequaltotwohundredcolordot"></div> '.$lessorequaltotwohundredcounter.'  <div class="greterthantwohundercolordot"></div> '.$greterthantwohundercounter.'</div></div>';
echo '<a href="#'.$winningc.'" class="gotobtn"><div class="col-md-4 col-sm-5 col-xs-12 winning-c-col"> <div class="pull-right winning-c '.$winnerboxinvisibility.'"><p><b>Winner: </b>'.$winningc.'</div></div></a>';
echo '<div class="col-md-2 col-sm-3 col-xs-12 total-cont-col"> <div class="pull-right total-cont"><p><b>Label: </b>'.number_format($variablename,2).'</p></div></div>';
echo '</div>';

echo '<div class="row">';
echo $displayall;
echo '</div>';


?>

custom.js

var currentlyvisibletab;

$('.nav.navbar-nav a').on('click',function(event)
{
    event.preventDefault();



     loadthisdatetimetab = $(this).attr('href');
     $('.datetimetab').hide();
    $(loadthisdatetimetab).show();

    $('.currentlyvisibletab').val(loadthisdatetimetab);
    currentlyvisibletab = loadthisdatetimetab;


});

setInterval(
function ()
{
    $.ajax(
            {
               type: "POST",
               url: "timecheck.php",
               datatype: "json",
               success: function(data)
               {

                    if(data != 'no')//if not scheduled time to change tabs
                    {
                       if($('.currentlyvisibletab').val() != data)
                       {//data is either #today, #tomorrow , #yesterday
                           $('.currentlyvisibletab').val(data);
                            currentlyvisibletab = data;


                          $(currentlyvisibletab).siblings().hide();
                          $(data).show();


                       }
                    }
               }
            });
}, 3500);

function ()
{
$('#today').unload().load('today.php').fadeIn('slow');




$('#tomorrow').unload().load('tomorrow.php').fadeIn('slow');



$('#yesterday').unload().load('yesterday.php').fadeIn('slow');

$(currentlyvisibletab).siblings().hide();
$(currentlyvisibletab).show();
}, 10599);



function onloadct()/*for <body onload="onloadct()">*/
{

    if(window.location.hash)
    {
        // Fragment exists
        var hashvalue = window.location.hash;


        $('.datetimetab').hide();
        $(hashvalue).show();

        currentlyvisibletab = hashvalue;

    } else
    {
        // Fragment doesn't exist

        $.ajax(
            {
               type: "POST",
               url: "onloadchecktime.php",

               datatype: "json",
               success: function(data)
               {


                       if($('.currentlyvisibletab').val() != data)
                       {
                           $('.currentlyvisibletab').val(data);
                            currentlyvisibletab = data;


                          $(currentlyvisibletab).siblings().hide();
                          $(data).show();


                       }

               }
            });
    }

}


/*as suggested in the answer and comments but still doesn't work. removed unbind because it stopped twitter bootstrap navbar from working when collapsed */



  $(document).ready(function() {
      $(document).on('click', '.gotobtn', function(event) 
     {


    // prevent default behavior (getting the # in the URL)
    event.preventDefault();
    // get the id of the element that you want to scroll to
    var gotothisid = $(this).attr('href');
    // scroll the html/body as many pixels as the target element's position
    $("body").animate({ scrollTop: $(gotothisid).offset().top });
  });
});
Community
  • 1
  • 1

3 Answers3

0

You could achieve this by using the animate() method, and scrolling the html/body to the element once the link is clicked (after preventing the default behavior that would be putting the # in the URL).

To calculate the amount of pixels to scroll, you can use the offset() method that will return the pair of coordinates of the element (you will focus in .offset().top for vertical scrolling). Then use a similar method to the one explained in Nick's solution to scroll the html and body with scrollTop.

A simple demo:

$(document).ready(function() {
  $(document).unbind().on('click', '.gotobtn', function(event) {
    // prevent default behavior (getting the # in the URL)
    event.preventDefault();
    // get the id of the element that you want to scroll to
    var gotothisid = $(this).attr('href');
    // scroll the html/body as many pixels as the target element's position
    $("html, body").animate({ scrollTop: $(gotothisid).offset().top });
  });
});
p { margin-bottom: 12px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><a href="#scrolltothiselement" class="gotobtn">click</a></p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<div id="scrolltothiselement">Yes! Scroll here.</div>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
<p>Nope.</p>
Community
  • 1
  • 1
Alvaro Montoro
  • 23,383
  • 6
  • 47
  • 81
-2

You should read about anchors to see that what you're trying to do is the default behavior of the browser.

ThibaultV
  • 480
  • 1
  • 5
  • 21
  • I know.. I am trying to prevent #stuff on the url to make my code less complicated. I already have code that makes my site behave differently if it detects some #stuff on the url. – Johanna Cristine Dy Dec 23 '15 at 15:36
-3

Try assigning the on handler to the parent element.Notice the a in the selector that is missing in your code.

$(document).on('click','a.gotobtn',function()
    {

          //your code


    });

The on method can be bound to the parent elements and then the click will dynamically attach to any children of that element that load after the original DOM setup. As long as each new element you append to a is called "gotobtn" it should work.

You can find a more in depth answer here

Community
  • 1
  • 1
Korgrue
  • 3,237
  • 1
  • 10
  • 19
  • This isn't any different than what the OP said she tried. – andi Dec 23 '15 at 15:39
  • He is not delegating. He is assigning the handler directly to `gotobtn`. Not its parent anchor element. Look at my code close and then his. – Korgrue Dec 23 '15 at 15:40
  • 1
    No they are assigning the handler to document: `$(document).on('click','.gotobtn',` is what OP has its the same thing you have except you are limiting it to anchor tags with class gotobtn – Patrick Evans Dec 23 '15 at 15:44
  • The `a` element is the parent element. He is trying to target anchors according to his code. So long as the original instance of the anchor persists, adding a new class to it delegates the anchor as the click handler - even if the classname did not exist at the original DOM setup. The way he is doing it, he is not delegating to any new links that are added after the original DOM setup. My method may not be the best - but in testing it works. – Korgrue Dec 23 '15 at 15:54
  • 2
    We aren't saying its not the best we are saying its the the same thing they are already are doing. `$(document).on('click','a.gotobtn'` is the same thing as `$(document).on('click','.gotobtn'` the only difference is that the latter will target any element with class `gotobtn` while the former only targets anchors with class `gotobtn` – Patrick Evans Dec 23 '15 at 15:58