I have an application containing a form with five input fields. When the user clicks on an input field a tooltip should be displayed, which works fine. The problem comes when I try to remove the tooltip, which happens if the user clicks on another input field. Below is a piece of code from my application, and I hope it’s enough to understand how it works.
The arguments that are passed to “showTooltip()” are a DOM reference to the clicked input field, the text that is displayed in the tooltip, and a number (0-4) that is used to find the containing div that’s surrounding the clicked input field (all input fields are inside their own div).
The application works fine, but after I’ve clicked around a couple of times on the fields the following message is displayed in the console: “Node was not found – inputDiv.removeChild(tooltip). I’ve found out that the reason for this is that the function “hideTooltip()” is sometimes called twice, but I can’t find out the reason why this happens.
Any clues?
showTooltip: function(inputField, tooltipText, divNr){
var container = document.getElementById('container');
var inputDiv = container.getElementsByTagName('div');
var inputDiv = inputDiv[divNr];
var tooltip = document.createElement('div');
tooltip.className = "tooltip";
var text = document.createTextNode(tooltipText);
tooltip.appendChild(text);
inputDiv.appendChild(tooltip);
inputField.addEventListener('blur', function() { hideTooltip(inputField, inputDiv, tooltip, inputNode);});
},
hideTooltip: function(inputField, inputDiv, tooltip, nr){
inputDiv.removeChild(tooltip);
validateField(inputField);
}
unbindis jquery function, so it will not work unless you are using jquery. You will need to use theremoveEventListenerfunction without jquery. If you do decide to use jquery, I would recommend theone(http://api.jquery.com/one/) function that executes an event only once per element. I am not sure if you will need to check to see if the event exists before you callremoveEventListener.