Jessica
Jessica

Reputation: 3769

How can I add a HREF attribute to <a> links with jQuery and is href always needed?

I have the following:

<div class="style-switcher"  id="colorChanger">
    <a style="background-color: #FFFFFF;" data-style="arctic" title="Arctic"></a>
    <a style="background-color: #F2F2F2;" data-style="aristo" title="Aristo"></a>

I am using this code to allow me to change styles. What I do is that I run the following code to add click events:

    $('.style-switcher a').retheme({
            baseUrl: '/Content/Themes-jQuery',
            themeName: 'jquery-ui-1.8.17.custom.css',
            loadingImg: '/Scripts/user/styles/img/loading.gif',
            delay: 500
            }, function () {
                var theme = $(this).attr('href');
                }
            );

Originally I had href="#" included in each link. Can you tell me do I always need to have this even if the link is not really used to go to anywhere.

If I do require it then is there a way I could add this with jQuery rather than entering in href="#" on every style line?

Upvotes: 0

Views: 87

Answers (4)

Alexander St&#248;ver
Alexander St&#248;ver

Reputation: 645

The attribute is not required. If you decide to use it you can set it with jQuery using .attr(). Depending on the browser, certain visual styles are not applied to the A element without the HREF attribute. This is easily fixed with CSS but worth noting.

Here's how to check the document for all A elements without the HREF attribute and set it:

$('a:not([href])').attr('href', '#');

Upvotes: 0

giker
giker

Reputation: 4245

You can remove normal behavior by "prevenDefault".

$('.style-switcher a').click(function(e){
       e.preventDefault();
       // your javascript here.
})

Upvotes: 1

Madbreaks
Madbreaks

Reputation: 19549

From the W3C Docs:

The href attribute makes this anchor the source anchor of exactly one link. Authors may also create an A element that specifies no anchors, i.e., that doesn't specify href, name, or id. Values for these attributes may be set at a later time through scripts.

There you have it. As for how w/ jQuery:

$('a').attr('href', '#');

...or whatever you want to set it to.

Cheers

Upvotes: 1

Yorgo
Yorgo

Reputation: 2678

yes yo should use href attribute to display anchor as styled in css.

$(function(){$("a").attr({
    href: "javascript:void(0)"})
});

or

$(function(){
   $("a").attr({href: "#"})
});

Upvotes: 1

Related Questions