Question

I have this script. As simple as I could think to make it.

<script type="text/javascript">
        $(document).ready(function () {
            $("a.textlink").click(function () {
                $("#WritingContent").load(this.attr("href"))  
            });
        });
</script>

and this link:

<a href="Writings/test.txt" class="textlink">test</a> (and a bunch of other similar links)

It's supposed to load that text file contents into the specified div is it not? When I click that link, all that happens is it opens up the text file. It doesn't load it into the div.

What is REALLY going on here is I have a slew of unformatted .txt files and I want to do the following:

  • wrap the first line in <h2> tags
  • wrap each subsequent paragraph in <p> tags
  • output the results to the #WritingContent div

still very much new to jQuery. Have not been able to research a solution.

Was it helpful?

Solution

You have two issues in your code that I noticed. As mentioned in the comments, clicking a link will open that link.

And as one of the answers by Adil mentioned, you can access the link's href by using JQuery attr

$("#loadText").attr("href");

or DOM attr

var a = document.getElementById("loadText"); 
a.href;

Secondly, to prevent the page from opening the file/redirecting to the file, one way is to change the href attribute of the link and add the real file address to a different attribute of your own choice.

//now href will not redirect your page to anywhere, it will just append some text to the url.    
<a href="#loadText" addref="Writings/test.txt" class="textlink">test</a>

$(document).ready(function () {
    $("a.textlink").click(function () {
        $("#WritingContent").load($(this).attr("addref")) //accessing addref instead of href
    });
});

Another way is to keep the link as it as with it's original href but prevent redirecting/opening the file on link click

 $(document).ready(function () {
    $("a.textlink").click(function (e) {
         e.preventDefault();//here we prevent the link from doing it's what it was meant to do, linking! 
        $("#WritingContent").load($(this).attr("href"))  
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top