user2994429
user2994429

Reputation: 105

Javascript 'onclick' table issue

I do apologize for the title, I wasn't sure what to call this. Anyways I am currently working on a WYSIWYG site builder and I've run into a little problem.

I created the following code to automatically make a 'div' appear above the selected cell for some buttons to be contained within it. The 'div' needs to disappear when a user clicks on another cell or when the user clicks on another bit of the document, etc. But I've been unable to figure out a good method of getting rid of it, would be lovely to have some help. Thank you, and also if it isn't too much to ask. I've been attempting to figure out a way for the document to automatically detect what table index is selected from where the user has their cursor. That can be seen on line 1.

http://jsfiddle.net/fwZTc/102/

var table = document.getElementsByTagName("table")[0];
var cells = table.getElementsByTagName("td"); // 

for(var i = 0; i < cells.length; i++){
// Cell Object
var cell = cells[i];
// Track with onclick


cell.onclick = function(){
    var cellIndex  = this.cellIndex;  

    var rowIndex = this.parentNode.rowIndex;

    alert("cell: " + cellIndex + " / row: " + rowIndex );

//var div = document.createElement('div');
//div.innerHTML = "my <b>new</b> skill - <large>DOM maniuplation!</large>";
// set style
//div.style.color = 'red';
// better to use CSS though - just set class
//div.setAttribute('class', 'myclass'); // and make sure myclass has some styles in css
//document.appendChild(div);


awesome = table.rows[rowIndex].cells[cellIndex];
awesome.innerHTML = '<div style="width:200px; height:20px; position:absolute; margin-top:-20px; background-color:#666">'
}
}

Upvotes: 0

Views: 104

Answers (1)

Navin
Navin

Reputation: 604

Try this instead.

HTML:

<table>
<tbody id="myTblBody">
    <tr>
        <td>1</td>
        <td>2</td> 
        <td>3</td>
    </tr>

    <tr>
        <td>4</td>
        <td>5</td>
        <td>6</td>
    </tr>

    <tr>
        <td>7</td>
        <td>8</td>
        <td>9</td>
    </tr>
</tbody>

JQuery:

$('#myTblBody tr td').click(function(){
  var html = $(this).html();
  $('#box').remove();
  $(this).html(html + '<div id="box" style="width:50px; height:20px; position:absolute;             margin-top:-20px; background-color:#666">');
  //If you would like to know row and col number.
  var row = $(this).parent().index();
  var col = $(this).index();
  alert('row ==' + row + "col == "+ col);
});

JSFiddle

Upvotes: 1

Related Questions