user742030
user742030

Reputation:

Proper Syntax to Pass Vars in a href JavaScript

Basic question so I feel dumb but..., Whats the proper syntax below in the href?

The href:

<html>
<a href="javascript:navClickListener("navContent", "bodyContent" "http://somelink.com");"></a>
</html>

The Function:

function navClickListener(appendE, target, gotoURL) {
    //doing stuff
};

Upvotes: 0

Views: 148

Answers (3)

Matthew Darnell
Matthew Darnell

Reputation: 4588

Using javascript:void(0); as the HREF value will prevent jumping or other undesired behavior from happening when the user clicks on the anchor. Use single quotes since you have double quotes in your JavaScript.

<a href="javascript:void(0);" onclick='javascript:navClickListener("navContent", "bodyContent" "http://192.168.1.34/wiki/index.php/Airworthiness_Directive #content");'></a>

Alternatively, you can do the entire thing in your JavaScript by binding a click handler. This would allow you to set a normal HREF value, which would be better for screen readers, and still allow the same functionality.

<a href="http://192.168.1.34/wiki/index.php/Airworthiness_Directive#content" class="someclass"></a>

$(document).ready( function() {
    $('.someclass').click( function(event) {
        event.preventDefault();//Does the same thing as javascript:void(0); in the HREF value
        var pageURL = $(this).attr('href');
        navClickListener("navContent", "bodyContent", pageURL );
    } );
} );

Upvotes: 1

Pointy
Pointy

Reputation: 413717

You'd be better off avoiding JavaScript in your "href" attributes.

<a href='#' onclick='navClickListener("navContent", "bodyContent", "http://192.168.1.34/wiki/index.php/Airworthiness_Directive #content"); return false;'>Click Me</a>

Upvotes: 1

Rob W
Rob W

Reputation: 349002

When you really have to use inline JavaScript, use different quotes, eg ' or &quot;.
Currently, the HTML attributes are marked by double quotes, as well as the JavaScript code.

<a href="javascript:navClickListener("navContent", "bodyContent" "http://192.168.1.34/wiki/index.php/Airworthiness_Directive #content");"></a>
Is effectively truncated to:
<a href="javascript:navClickListener("></a>
                                     ^ Because of this.

In this case, since you're using a JavaScript-URI, you can also use %22 instead of double quotes.

Demo: http://jsfiddle.net/pu3CM/

Upvotes: 2

Related Questions