user6322822
user6322822

Reputation:

Link positioning inside of div;

Okay below I have posted the script I'm using and the #targetDiv, Basically my problem is when I move the link that is currently contained within the #targetDiv outside of the div, The link no longer loads the page inside of the div, Is there a way I can move the link outside of the #targetDiv and still have it load the page contents inside of the div.

Script

$(function(){
    $('#targetDiv').on('click', 'a', function(e){
         e.preventDefault();// prevent browser from opening url
         $('#targetDiv').load(this.href);   
    });
});

Div

<div id="targetDiv" class="collapse">
<a href="/page.php">Load</a>
</div>

The problem I have is that I want the load link to be outside of the target div however when I move it outside of the div it loads the main page not the content within the targetDiv.

What I'm trying to achieve;

<a href="/page.php">Load</a>
<div id="targetDiv" class="collapse">
</div>

Upvotes: 0

Views: 43

Answers (2)

charlietfl
charlietfl

Reputation: 171689

Add a class to any links you want to use to load content

<a class="content-link" href="/page.php">Load</a>

And modify event listener accordingly so it handles both types of links

    $(document).on('click', '.content-link, #targetDiv a',function(e){
         e.preventDefault();// prevent browser from opening url
         $('#targetDiv').load(this.href);   
    });

Upvotes: 1

cssyphus
cssyphus

Reputation: 40076

Try this:

$(function(){
    $('#divLoad').click(function(e){
         e.preventDefault();// prevent browser from opening url
         $('#targetDiv').load(this.href);   
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<a id="divLoad" href="/page.php">Load</a>
   <div id="targetDiv" class="collapse">
</div>

You can also do this (more difficult to be precise):

$(function(){
    var divLoad = $('#targetDiv').prev('a');
    //alert(divLoad.attr('href') );
  
    divLoad.click(function(e){
         e.preventDefault();// prevent browser from opening url
         $('#targetDiv').load(this.href);   
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<a id="divLoad" href="/page.php">Load</a>
   <div id="targetDiv" class="collapse">
</div>

Upvotes: 0

Related Questions