Search code examples
javascriptjqueryhtmlcssanchor

How to change CSS link on click of <a> tag?


I have been trying for hours to get my anchor tags to work that if clicked, it changes the href of a link pointing to a color theme CSS.

Here is what i got and discovered so far. I have only been trying to change it to the red theme.

the html (white spaces removed between list tag to prevent gaps in visuals caused by inline-block)

<header>
  <ul>
   <li>
    <a id="theme_selector_red" href="" onclick="applyCSS('css/theme_red.css');"></a>
   </li>
   <li>
    <a id="theme_selector_green" href=""></a>
   </li>
   <li>
    <a id="theme_selector_blue" href=""></a>
   </li>
  </ul>
 </header>

the link tag

<link id="color_theme" type="text/css" rel="stylesheet" href="css/theme_blue.css">

the javascript i tried the .attr() in different ways, also tried removing and resetting attributes with no luck. The alert is just to test if clicking is getting to the function, and yes, the website shows the alert every time I click on the link.

function applyCSS(css_link){
   $('#color_theme').attr("href", css_link);
   document.getElementById('color_theme').removeAttribute('href');
   document.getElementById('color_theme').setAttribute('href', css_link);
   alert('hey');
};

The link tag works, it's just not changing it's href when I click on the link. :(


Solution

  • Change onclick to this:

    onclick="applyCSS('css/theme_red.css'); return false;"
    

    Currently, after running applyCSS, it follows the link and refreshes the page. "return false" will prevent that behavior.