0

I used the following codes posted as the accepted answer in Toggle classname onclick JavaScript

It works great in all browsers, even in old version IE (my project needs this IE support). The only change I made is using this.className instead of myButton.classname in the 2nd line since IE would give error to myButton.classname ('myButton' is undefined).

My question is: even it works, why Eclipse complains by showing a red X beside the last line? If I hover mouse over the red wave under the last } (in the last line), it shows: "Multiple annotations found at this line: - Syntax error, insert "}" to complete MethodBody- Syntax error, insert ")" to complete Expression". This error does occur even if I did not make the above change.

If I add ; after the last } (thinking the function is a part of an executable statement), Eclipse still complains although it continues to work.

Could anyone please give any hints?

document.getElementById('myButton').onclick = function() {

    var className = ' ' + this.className + ' ';

    if ( ~className.indexOf(' active ') ) {
        this.className = className.replace(' active ', ' ');
    } else {
        this.className += ' active';
    }              
}
Brian
  • 1
  • 2
  • 1
    I don't know why eclipse is telling you this. But I see two issues with the code you posted. The first is the ~ in from on className in the if statement. Maybe a typo or else something I don't understand in JavaScript? The second is the use of className. Maybe this is necessary for IE compatibility, but otherwise I would recommend using classList instead – ControlAltDel Apr 29 '22 at 19:29
  • 2
    @ControlAltDel see https://stackoverflow.com/questions/12299665/what-does-a-tilde-do-when-it-precedes-an-expression - it's a rather oldfashioned idiom for checking if a number is -1, nowadays you'd just use `className.includes(' active ')`. Agree on the use of `classname` instead of `classList`. – Robin Zigmond Apr 29 '22 at 19:33
  • 1
    Thank you for the reply! ~ is the tilde operator (https://wsvincent.com/javascript-tilde/) and it serves the purpose in this case. Yes I agree with using classList, but I have to support IE old versions, so className is needed. Also thanks @Robin Zigmond for confirming. – Brian Apr 29 '22 at 19:36
  • I cannot reproduce this in the current Eclipse. Which Eclipse version do you have? Which JavaScript editor do you use (WTP or WWD) of which version? – howlger Apr 30 '22 at 12:59
  • @howlger Thanks for checking! I should have included this info. I am using Eclipse Oxygen.3a (4.7.3a) and WTP JSDT 2.1.1.v201804042202. So you were suggesting this may be an editor issue and I shall update it? Thanks a lot. – Brian May 02 '22 at 13:26

0 Answers0