YaddyVirus
YaddyVirus

Reputation: 301

How to use element id as JS function parameter in `onclick` function?

I'm trying to use my an anchor tag as a button running a JS function when clicked.

HTML -

<a  class="ghost-button-transition" href="#" onclick="navforward(about)" style="margin-right:5px;">About me</a>

JS -

function navforward(name){
  var str = "#"+String(name);
  $("#intro").fadeOut(1000).delay(1500);
  $(str).fadeIn(1000);
}

Whenever I click on my <a> tag I get the following error in the console -

Error: Syntax error, unrecognized expression: #[object HTMLDivElement]

Now I understand that this is happening because my navforward function is treating the name parameter as an object and hence can't really use it as a handle to call the respective HTML element. But why isn't it working even after converting the parameter to a string?

I have also tried- onclick="navforward("about") and onclick="navforward("#about") but they also gave errors.

How do I get this working?

Upvotes: 0

Views: 1190

Answers (3)

Rajkumar A
Rajkumar A

Reputation: 87

Try this one. If you pass this object in a method, you can access the whole DOM element.

<a id="about" class="ghost-button-transition" href="#" onclick="navforward(this)" style="margin-right:5px;">About me</a>

function navforward(obj){
  $("#" + obj.id).fadeOut(1000).delay(1500).fadeIn(1000);
}

Upvotes: 0

Zenoo
Zenoo

Reputation: 12880

Your about object is an HTMLDivElement.

Just use its id property instead of converting it to a String :

function navforward(name){
  let str = "#"+name.id;
  $("#intro").fadeOut(1000).delay(1500);
  $(str).fadeIn(1000);
}

As @Satpal pointed out in the comments, you can simply use your about object directly in your jQuery selector :

function navforward(name){
  $("#intro").fadeOut(1000).delay(1500);
  $(name).fadeIn(1000);
}

Upvotes: 3

Tanupriya
Tanupriya

Reputation: 167

Pass about as a string as:

HTML:

<a class="ghost-button-transition" href="#" onclick="navforward('about')" style="margin-right:5px;">About me</a>

JS:

function navforward(name){
  var str = "#"+name;
  $("#intro").fadeOut(1000).delay(1500);
  $(str).fadeIn(1000);
}

Upvotes: 0

Related Questions