1

I'm trying to load a HTML file into a div section, but the load() method doesn't seem to work as when I click the link, the html file opens in a new tab instead of loading into the div tag.

The script:

<script type="text/javascript">
        $(document).ready(function(){
            $('a').click(function(){
                $('#main-content').load($(this).attr("href"));
                return false;
            });
        });
</script>

The 'a' tag:

<li><a href="about.html">ABOUT</a></li>

Where I want my html file to be loaded:

<div class="col-sm-9 blog-main" id="main-content">
...
</div>

How do I make the load() method work?

I'm using Chrome on Windows.

Marco
  • 141
  • 2
  • 14

4 Answers4

1

That's the default behavior of a tag. Instead of setting the html.file to be loaded in href attribute, its better to keep it in custom attribute.

 <a href="#" data-page="about.html">ABOUT</a>

And in JavaScript,

<script type="text/javascript">
    $(document).ready(function(){
        $('a').click(function(e){
            e.preventDefault();
            $('#main-content').load($(this).attr("data-page"));
            return false;
        });
    });
</script>

Plunker sample

Developer
  • 5,545
  • 2
  • 16
  • 24
0

try about.html ensure that the file is in the root of the project

<li><a href="./about.html">ABOUT</a></li>
<div class="col-sm-9 blog-main" id="main-content"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> 
<script type="text/javascript">

$(document).ready(function(){
        $('a').click(function(event){
            event.preventDefault();
            $('#main-content').load($(this).attr("href"));
            return false;
        });
    });
</script>
Dev. Joel
  • 1,074
  • 1
  • 8
  • 13
0

You can use preventDefault to stop default action of the event to triggered.

<script type="text/javascript">
        $(document).ready(function(){
            $('a').click(function(event){
                event.preventDefault();
                $('#main-content').load($(this).attr("href"));
                return false;
            });
        });
</script>
Daksh
  • 33
  • 7
0
<script type="text/javascript">
        $(document).ready(function(){
            $('a').click(function(){
                $('#main-content').load($(this).attr("href") + ' #elementSelectorThatYouWantToLoad');
                return false;
            });
        });
</script>

You have to specify an DOM element that you want to load like,

$('#main-content').load($(this).attr('about.html #body');
Mijabi
  • 1