Friday, August 15, 2014

Javascript to Prevent Selecting Texts on Tabled Buttons


It is now a common phenomenon that HTML tables are made buttons to replace conventional image-based buttons. The benefits of tabled buttons are quick loading, good button quality when zoomed on tablets and easy to change color. There is also no need to perform pre-loading.

This new popular method of displaying buttons can sometimes perform awkwardly if the text selection is not turned off on the tabled button. The following shows my javascript of disabling the text selection on a table.


<table>
<tr>

<td width=100 bgcolor=yellow id=box1 onclick="func1()" onmouseover="over(this)" onmouseout="out(this)" align=center>Box 1</td>
<td width=100 bgcolor=yellow id=box2 onclick="func2()" onmouseover="over(this)" onmouseout="out(this)" align=center>Box 2</td>

</tr>
</table>

<script>

document.getElementById('box1').onselectstart = function() {return false;};

function func1() {
 alert('Box 1');
}

function func2() {
 alert('Box 2');
}

function over(elem) {
 elem.style.backgroundColor = "#ccddff";
 elem.style.cursor = "pointer";
}

function out(elem) {
 elem.style.backgroundColor = "yellow";
 elem.style.cursor = "default";
}


</script>


The screen capture of this HTML being run on browser:



Note that if your mouse is trying to select on "Box 1", it won't work. But it works for "Box 2", as the selection feature is not disabled by the Javascript.

No comments:

Post a Comment