0

I used someone else's code to try to load content into a div on a WordPress home page when a viewer clicked a headline in a list of headlines.

The headlines are all explanatory material on a particular topic. They don't work well as one long piece. I tried using the bootstrap accordion, but some of the sections are much long than others and go too low on the page for that to be an effective strategy. It looks pretty, but readers who were asked for feedback said they didn't think it worked.

AJAX seemed like a good solution; when it works, it looks great. The problem with the following AJAX code is that it works 90 percent of the time on my Firefox browser but not the other 10 percent. I can test it for hours and it's fine. And then I test it again, and suddenly nothing loads in the div. Would anyone be able to explain possible reasons for the failure? Feel free to suggest a better solution. Thank you.

The div:

<div class="col-sm-6" id="mystory-container"></div>

The code:

    jQuery(document).ready(function($) {

         $.ajaxSetup({cache:false});
        $(".mystory-link").click(function(){
            var post_link = $(this).attr("href");

            $("#mystory-container").html('Loading');
            $("#mystory-container").load(post_link);
        return false;
        });    
    });

1 Answer 1

0

changue this:

<script type="text/javascript">
$(".mystory-link").click(function(){
    // Your code;
    return false;
});
</script>

BY (This is the correct way to use jquery events):

<html>
<body>
<!-- anchors -->
<a class="mystory-link" href="https://www.google.com"></a>
<a class="mystory-link" href="https://www.yahoo.es"></a>
<a class="mystory-link" href="https://www.youtube.com"></a>

<!-- content -->
<div id="mystory-container"></div>

<!-- javascript -->
<script type="text/javascript">
$(document).on('ready', function(event) {

    // this method select all Class «mystory-link» in the «document»
    $(document).on('click', ".mystory-link", function(event){
        // stop the events by default in the anchors
        event.preventDefault();
        event.stopPropagation();

        // set link in one var
        var post_link = $(this).attr("href");

        // load the content in div
        $("#mystory-container").html('Loading...');
        $("#mystory-container").load(post_link);
    });

});

</script>
</body>
</html>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.