2

I have 3 divs + 3 hidden divs. I want to click on "service1" and edit "display:block" in "toggle1".

The HTML:

<div id="service1" onclick="changeService('toggle1')></div>
<div id="service2"></div>
<div id="service3"></div>
<br><br>
<div id="toggle1"></div>
<div id="toggle2"></div>
<div id="toggle3"></div>

The CSS:

#toggle1, #toggle2, #toggle3 {display:none}

The Javascript:

function changeService(this) {
    this.style.display = "block";
}

Hope I explained myself well enough so you guys can understand. What am I doing wrong?

Thanks in advance :)

3 Answers 3

2

You are passing a string into function, not an object. You can use document.getElementById method to get corresponding div element:

function changeService(id) {
    document.getElementById(id).style.display = "block";
}
Sign up to request clarification or add additional context in comments.

4 Comments

didn't work. you put "id" as an example or is that really id?
ok, I got it to work! thanks to you! :) BTW, why if I put "id" it works, and "this" does not?
Because this is a reserved word, and it can't be used in such context.
Ok. Thanks for the explanation! Will put right answer as soon as possible.
1

I think it would be best to use CSS classes.

So go:

#toggle1, #toggle2, #toggle3 {display:none}
#toggle1.active, #toggle2.active, #toggle3.active{display: block}

And then:

function changeService(id) {
    document.getElementById(id).setAttribute("class", "active");
}

Then you can keep view and logic separated and easily add more style if necessary. Try never to change your CSS in Javascript. Better add classes like this to keep things clear.

https://jsfiddle.net/t74tmu7r/2/

1 Comment

Thanks for the tip! Thanks to you and some more research I'm getting where I want jsfiddle.net/lordfox/n4dn9jur Now, I just need some way to find any "toggle active" div, and IF one is found, setAttribute("class", "toggle hidden"). But I will formulate another question for it.
0

first of all place your script file before the closing body tag to make sure all DOM elements are loaded then use this code:

function changeService(id){
  var elem = document.getElementById(id);
  elem.style.display = "block";
}

then in the div tag with a class name 'service1' do this:

<div id="service1" onClick="changeService('toggle1');"></div> 

that should do the job.

1 Comment

Thanks for the tip! Thanks to you and some more research I'm getting where I want jsfiddle.net/lordfox/n4dn9jur Now, I just need some way to find any "toggle active" div, and IF one is found, setAttribute("class", "toggle hidden"). But I will formulate another question for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.