0

Here's what I have so far:

function highlighton(id1, id2) {
document.getElementById(id1).classList.add('highlight');
document.getElementById(id2).classList.add('highlight');
}

function highlightoff(id1, id2) {
document.getElementById(id1).classList.remove('highlight');
document.getElementById(id2).classList.remove('highlight');
}

And the HTML code:

<span id="f000020" onmouseover="highlighton('f000020', 'f000020t')" onmouseout="highlightoff('f000020', 'f000020t')">It is impossible to say how first the idea entered my brain;</span>

<span id="f000020t" onmouseover="highlighton('f000020', 'f000020t')" onmouseout="highlightoff('f000020', 'f000020t')">Es imposible decir cómo es que por vez primera la idea entró a mi cerebro;</span>

The JSFiddle for further reference.

The idea is that if you hover either on english id span or spanish id span it would change the background for both at the same time. For unobtrusive requirements it has to toggle classes and for specific build restrictions it cannot use jQuery.

nicokruk
  • 59
  • 6
  • `+=` in that context means concatenation, but `-=` still means subtraction, of *numbers*. – elclanrs Jul 31 '14 at 01:30
  • 2
    Also, this is in modern browsers already, https://developer.mozilla.org/en-US/docs/Web/API/Element.classList – elclanrs Jul 31 '14 at 01:32
  • I got that from here: http://stackoverflow.com/questions/7388626/how-do-i-add-a-class-to-the-html-element-without-jquery Guess it's wrong – nicokruk Jul 31 '14 at 01:32
  • I changed the functions. Now they use classList methods, but still no luck. – nicokruk Jul 31 '14 at 01:51
  • In your shoes I'd look at [jquery's implementation](https://github.com/jquery/jquery/blob/c869a1ef8a031342e817a2c063179a787ff57239/src/attributes/classes.js) – jdphenix Jul 31 '14 at 01:59
  • There's a `toggle` method, check the link again. – elclanrs Jul 31 '14 at 02:01
  • I've fixed your fiddle, doing the following: **1.** Remove jQuery **2** use the classList.toggle method. See fiddle here: http://jsfiddle.net/5K6LC/16/ – enhzflep Jul 31 '14 at 02:09

1 Answers1

1

In this particular case you probably don't want .toggleClass() because you want to make sure a class is removed when the mouse moves out; it's not unlikely that some weird edge case would break a toggle state.

function highlighton(id1, id2) {
    document.getElementById(id1).classList.add("highlight");
    document.getElementById(id2).classList.add("highlight");
}

function highlightoff(id1, id2) {
    document.getElementById(id1).classList.remove("highlight");
    document.getElementById(id2).classList.remove("highlight");
}

Make sure that those functions are defined in the global scope, otherwise you can't use them from inline JavaScript. Better still is to register the event handlers from code using .addEventListener() (though, look out for IE < 9 browsers which use .attachEvent())

Demo

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309