views:

102

answers:

2

How to anchor paragraph in other HTML pages and in the same time highlighted the area where the pointed paragraph is located when click the the button in the current page?

I made this simple code in JavaScript just doing the anchor thing

Current page:

<html>

    <form>
        <input type=button value="open in new tab" onClick="goToURL2()">
    </form>

    <body>
        <script type="text/javascript">
        <!--
            function goToURL2() { window.open( "explanations.html#footwell"); }
        // -->
        </script>
    </body>
</html>

New page:

<html>
    <p><a name="footwell">
        O, say can you see by the dawn's early light?
    </a></p>
</html>

I think that "highlighted text" jQuery will be the best method but can't figure out how to do it with more than one html page.

+1  A: 

You can link to the new location by using the anchor, as you have already done. Then, on the new page, you can grab the hash value (window.location.hash) from the URL and highlight that particular element sharing the value.

// untested, but close enough to convey the point
$(function(){
  var theHash = window.location.hash.split("#")[1];
  $("a[name='"+theHash+"']").parent("p").addClass("highlight");
});
Jonathan Sampson
Your selector won't work because window.location.hash includes # character.
Robert Koritnik
Robert, fixed. Thank you for pointing that out.
Jonathan Sampson
+1  A: 

Add id to Anchor tag as well

jQuery selector will work faster when you use an id. Just take the #part from the URL and use it in jQuery selector.

Change your page 2 to:

<a id="footwell" name="footwell">...</a>

You can choose whatever animation you want to highlight your anchor or add a class like someone else suggested, but your highlighted part will stay as set by the class the whole time you'll keep it's CSS class setting. By using animation it will highlight like we're used to (even here on SO). With animation...

This is the code you have to put on your second page:

$(function() {
    $(window.location.hash).parent().animate(...)
});

You can of course use this plugin as well to not mingle with custom animations.

Robert Koritnik