I have a table with four rows, each one with an "id", and inside each one link with a text.
I want to change the innerHTML of the clicked link with the next one link innerHTML.
So if I have this:
ONE
TWO
THREE
FOUR
and I click on TWO for example, the result must be:
ONE
THREE
TWO
FOUR
As follows my code, which already change the order of the two first links, but it does the same if I click another link.
<html>
<head>
<script type="text/javascript">
function change()
{
var link = document.getElementsByTagName("a");
var i = 0;
var aux = link[i].innerHTML;
link[i].innerHTML = link[i+1].innerHTML;
link[i+1].innerHTML = aux;
}
</script>
</head>
<body>
<table border="1">
<tr id="1"><td>ONE</td></tr>
<tr id="2"><td>TWO</td></tr>
<tr id="3"><td>THREE</td></tr>
<tr id="4"><td>FOUR</td></tr>
</table>
</body>
</html>
I've been working on this all day and I can't see what else can I do. I'm starting with both Java and Javascript, so the use of arrays and the DOM and Javascript functions is new to me.
How does the code know which link was clicked? If you don't tell it, it can't deduce it magically.
First off, remove all those id attributes. They serve no purpose here and will only lead to confusion.
Next, pass this as the first argument of change: onclick="change(this);" and function change(link) {...}.
Now, rewrite your change function to find the right link to change link with, and do the swap as you are now.
Good luck.
You seem to want to do something like:
<style type="text/css">
.shifter {
color: blue;
text-decoration: underline;
cursor: pointer;
}
</style>
<script>
function shiftRows(e) {
var el = e.target || e.srcElement;
var row, tbody;
if (el.tagName.toLowerCase() == 'span' && el.className == 'shifter') {
row = el.parentNode.parentNode;
tbody = row.parentNode;
if (row.rowIndex > 0) {
tbody.insertBefore(row, tbody.rows[row.rowIndex - 1]);
}
}
}
</script>
<table id="t0" onclick="shiftRows(event);">
<tr><td><span class="shifter">0</span>
<tr><td><span class="shifter">1</span>
<tr><td><span class="shifter">2</span>
<tr><td><span class="shifter">3</span>
</table>
Related
The code supposed to be use javascript between the <script> tags that
consists of a mouseover event, and the list items in the HTML page must
be styled as follows: normal - black, 12, bold and over yellow, 15, bold, italic.
<html>
<head>
<title> Using mouseover eve </title>
<script language = "javascript">
<!--
function changeStyle() {
var item = document.getElementByTagName("li");
item.style.color = "yellow";
item.style.fontSize = "15pt";
item.style.fontWeight = "bold";
item.style.fontStyle = "italic";
}
-->
</script>
</head>
<body>
<ul style = "color: black; font-size: 12pt; font-weight: bold" >
<li onMouseOver = "changeStyle()"> item 1 </li>
<li onMouseOver = "changeStyle()"> item 2 </li>
</ul>
</body>
</html>
That's because the correct function name is getElementsByTagName and not getElementByTagName.
var items = document.getElementsByTagName("li");
This will return a Nodelist of elements with that particular tag name (in this case, all list items in the document).
Then, you could target your li's specifically as you wish, for example:
items[0].style.color = "yellow"; // first li is yellow when mouseover
items[1].style.color = "red"; // second li is red when mouseover
etc.
The correct name for the function is getElementsByTagName (with an 's') and it returns an array of elements, not just a single one. If you want to get the first item from the array you will need to do somethig like this:
var item = document.getElementsByTagName("li")[0];
it should be document.getElementsByTagName
I have this code,
HTML and php
<?php for($i = 1; $i <= 5; $i++) { ?>
<div class="file-add-row" style="display:none;">Some content</div>
<?php } ?>
<div id="add-file-plus">Add File</div>
and the JS is
$('#add-file-plus').live('click', function () {
if($('div.file-add-row:visible').length == 0) {
$('div.file-add-row:hidden:first').show();
} else {
$('.file-add-row:hidden:first').removeAttr("style").insertAfter($('.file-add-row:visible:last'));
}
});
Now, my problem is, when I click the add button for the first time, the first 'file-add-row' div is displayed. But when I click the add button the second time, nothing happens on the page. Instead, it just completely removes that div from the dom.
I am just a beginner in jquery, so there might be things I overlooked. Anyone got any idea about what's going on ?
When you do:
$('.file-add-row:visible:last')
Just after:
$('.file-add-row:hidden:first').removeAttr("style")
They both refer to the same object. And if you try to insert an object after itself, it will end up removing itself from the DOM.
Change the JS to:
$('#add-file-plus').live('click', function () {
if($('div.file-add-row:visible').length == 0) {
$('div.file-add-row:hidden:first').show();
} else {
var last_visible = $('.file-add-row:visible:last')
$('.file-add-row:hidden:first').removeAttr("style").insertAfter(last_visible);
}
});
Demo (Click on 'Add File'):
https://jsfiddle.net/woxd2jbf/1/
Here's a version without jQuery just plain JavaScript, it will work with divs just as it does with button, ul, and li. The details are commented within the source.
Key Methods
cloneNode()
appendChild()
PLUNKER
SNIPPET
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!--This <li> is a template to clone-->
<li class="row" style='display:none'>Some content</li>
<!--This is the empty list to be populated with clones-->
<ul id='list'>
</ul>
<!--This button will have an eventListener
that will execute a function when it is clicked-->
<button id="add">Add File</button>
<script>
/* Reference each element involved in process */
// The button
var add = document.getElementById('add');
// The list
var list = document.getElementById('list');
// The first li
var row = document.querySelector('.row:first-of-type');
/*
1. Button will listen for a `click`
2. Create a clone of the first li
3. Add clone as the last child of list
4. Set clone's display property to block
so it's visible
*/
add.addEventListener('click', function(e) {
var clone = row.cloneNode(true);
list.appendChild(clone);
clone.style.display = 'block';
}, false);
</script>
</body>
</html>
$('.file-add-row:hidden:first').removeAttr("style").insertAfter($('.file-add- row:visible:last'));, due to this line the issue is happening. because it first removes the style attribute which makes it visible so $('.file-add- row:visible:last') is returning itself. refactor to store the visible el's reference like below:
$(function () {
$('#add-file-plus').live('click', function () {
if ($('div.file-add-row:visible').length == 0) {
$('div.file-add-row:hidden:first').show();
} else {
var $el = $('.file-add-row:visible:last');
$('.file-add-row:hidden:first').removeAttr("style").insertAfter($el);
}
});
})
I am trying to click on each cell on the table so that the selected cells I click on change the background color from white to gray. I am also trying to make it like a toggle so if I click on the cell again the background changes from gray to white, but it is not doing anything. I found a similar question, but the answer was advanced coding. I want to create a simpler code. I checked Firebug, but I do not see any errors. I would appreciate any suggestions. I am new to Javascript.
http://jsfiddle.net/RE006/nyzswnx2/1/
HTML5:
<table class="bingo">
<tr>
<td id="square0"></td>
<td id="square1"></td>
<td id="square2"></td>
</tr>
<tr>
<td id="square3"></td>
<td id="square4"></td>
<td id="square5"></td>
</tr>
<tr>
<td id="square6"></td>
<td id="square7"></td>
<td id="square8"></td>
</tr>
</table>
JS:
var toggleHighlight = function () {
document.td.style.backgroundColor = "#cecece;"
}
window.onload = function () {
getElementsByTagName("td").onclick = toggleHighlight ();
}
First of all: document.getElementsByTagName('td') returns a NodeList and not a single node, so you have to cycle on it to attach the event listener:
JS:
window.onload = function () {
var tds = document.getElementsByTagName("td");
for (var i = 0; i < tds.length; i++)
tds[i].onclick = toggleHighlight;
}
Please note that in the row tds[i].onclick = toggleHighlight;, toggleHighlight doesn't have ( and ) because it is a reference to a function and not a call to a function.
If you want to do things the web dev way, you should use classes instead of setting the color explicitly, so you can have:
JS:
function toggleHighlight() {
var td = this;
if (td.className == 'highlight')
td.className = '';
else
td.className = 'highlight';
}
CSS:
.highlight {
background-color: #cecece;
}
You can see the working example here: http://jsfiddle.net/nyzswnx2/40/
Please note that in order to make window.onload work I selected No wrap - in <body> instead of onLoad in the top left dropdown.
Note that
document.getElementsByTagName returns an array.
when you set onclick, you're going to need a function (function() {}), not the return value of that function (which is undefined in your example of onclick = toggleHighlight ();)
As per your JavaScript, you might want to try something like
var toggleHighlight = function (e) {
var bg = e.target.style.backgroundColor;
if (bg == 'red') {
e.target.style.backgroundColor = '';
} else {
e.target.style.backgroundColor = 'red';
}
}
var prepareTable = function () {
var cells = document.getElementsByTagName("td");
for (var i = 0 ; i < cells.length ; i++) {
cells[i].onclick = function(event) {
toggleHighlight(event);
}
}
}
document.onload = prepareTable();
Fiddle: http://jsfiddle.net/nyzswnx2/47/
you can use jQuery it's more simple.
add a class css :
.gray {
background-color:#efefef;
}
and change your code js with :
$(document).ready(function(){
$('td').on('click',function(){
$(this).toggleClass('gray');
});
});
Demo :
http://jsfiddle.net/nyzswnx2/51/
getElementsByTagName("td").onclick = toggleHighlight ();
First, this line is wrong, since getElementsByTagName() returns a list one is in need for a loop.
var tL = getElementsByTagName("td");
for(var i=0, j=tL.length; i<j; i++) tL[i].onclick = function(){this.style.backgroundColor = "#cecece"}
There is another possibility. Instead of defining an onclick() event for each cell in the table one could use onclick() event on the table and later on use the function document.elementFromPoint() to get the td. Yet the way used in the post (onclick() event on td) is pretty much standard.
To toggle the colors one needs to check whether colors are set yet or not (cecece in this case).
Example
<html>
<head>
<script>
function Init(){
document.querySelector('table').onclick = function(event){colorCell(event)}
}
function colorCell(event){
var tE = document.elementFromPoint(event.clientX, event.clientY);
if (tE.tagName === 'TD') tE.style.backgroundColor = (tE.style.backgroundColor === '') ? '#cecece' : ''
}
</script>
</head>
<body onload = 'Init()'>
<table>
<tr>
<td>0.0</td>
<td>0.1</td>
<td>0.2</td>
</tr>
<tr>
<td>1.0</td>
<td>1.1</td>
<td>1.2</td>
</tr>
<tr>
<td>1.0</td>
<td>1.1</td>
<td>1.2</td>
</tr>
</table>
</body>
</html>
First things first: your fiddle is already set to run the code on window.onload, so you have no need to repeat it. You can just write the code and it will automatically be executed upon load.
Now, for your question: you are attempting to assign an event listener to a Node Collection, while you really want to assign the event listener to each element of said collection. There are many ways to go about it, but you can safely do it like this:
var cells = document.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener('click', toggleHighlight);
}
Please note two things:
I've used addEventListener instead of assigning the function to the onclick event. I encourage you to look up both ways of assigning events.
When assigning a function to an event or, generally speaking, referring to a function as a variable, you should NOT call the function, but simply refer to it by its name. In this example, I have passed the toggleHighlight function to the addEventListener function as its second parameter just by passing it the name of the function, not by calling it. If you were to call the function, the second parameter passed to the addEventListener function would be the return value of the toggleHighlight function, not a reference to the function itself. I encourage you to look up the differences between calling a function in JavaScript and passing a function as a reference.
Let's take a look to the toggleHighlight function now: this function is somehow special, because it responds to an event. As such, its first parameter is a reference to an event itself, and the function should therefore be written like this:
function toggleHighlight(event) {
var cell = event.target;
cell.style.backgroundColor = '#cecece';
}
See what I did there? I used the event object to get the target of the event, and I've set the style on the target itself. Every time a cell is clicked, the target of the event will refer to the cell on which the event was triggered.
Toggling the color requires your code to be stateful: it must somehow save the state of each cell, and use it to decide which color should be used for the background of the cell. Sure, we could use the color of the cell as a state, but that's not really acceptable so we're going to do some more work to get things working. The first thing you want to do is define the states that will be available, and store the initial state of each cell somewhere. We could updated our code like so:
const SQUARE_OFF = 0;
const SQUARE_ON = 1;
var cells = document.getElementsByTagName('td');
var cellStates = {};
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener('click', toggleHighlight);
cellStates[cells[i].id] = SQUARE_OFF;
}
Let's look at what I did:
I declared two constants, one for each state, and assigned an arbitrary value to each of them. This is NOT the only way to do it, it's just one way;
I declared the cellStates variable as an empty object. We'll use this to store the states of each cell;
While looping through the cells, I used the current cell's id as the key to be used to store the cell's state within the cellStates object. Initially, all cells are going to be off. At the end of the loop, your cellStates will have a key for each cell with the cell's state stored within.
Now that we have saved the state, we want to update it every time we click on a cell, and change the color of the cell accordingly. Let's update our toggleHighlight function:
function toggleHighlight(event) {
var cell = event.target;
var cellState = (cellStates[cell.id] === SQUARE_OFF) ? SQUARE_ON : SQUARE_OFF;
cellStates[cell.id] = cellState;
cell.style.backgroundColor = (cellState === SQUARE_OFF) ? '#fff' : '#cecece';
}
And, just like that, you can now toggle the color of each cell upon clicking. I encourage you to experiment and understand what's going on here very carefully before moving on to other topics. Have fun and happy learning!
Complete fiddle: http://jsfiddle.net/nyzswnx2/29/
I like to delegate
Vanilla JS
window.addEventListener('load', function(e) {
document.getElementById('tb').addEventListener('click', function(e) {
const tgt = e.target.closest('td');
if (tgt) tgt.classList.toggle('selected')
})
})
table,
th,
td {
border: 1px solid #000;
border-collapse: collapse;
font-size: 1.0rem;
margin: 25px auto 0px auto;
text-align: center;
}
th,
td {
padding: 5px 10px;
}
/* bingo table */
.bingo td {
color: #000;
padding: 20px;
}
.bingo .selected {
background-color: red;
}
<table class="bingo">
<tbody id="tb">
<tr>
<td id="square0"></td>
<td id="square1"></td>
<td id="square2"></td>
</tr>
<tr>
<td id="square3"></td>
<td id="square4"></td>
<td id="square5"></td>
</tr>
<tr>
<td id="square6"></td>
<td id="square7"></td>
<td id="square8"></td>
</tr>
<tbody>
</table>
jQuery
$(function() {
$('#tb tbody').on('click', 'td', function(e) {
$(this).toggleClass('selected')
})
})
table,
th,
td {
border: 1px solid #000;
border-collapse: collapse;
font-size: 1.0rem;
margin: 25px auto 0px auto;
text-align: center;
}
th,
td {
padding: 5px 10px;
}
/* bingo table */
.bingo td {
color: #000;
padding: 20px;
}
.bingo .selected {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table class="bingo" id="tb">
<tbody>
<tr>
<td id="square0"></td>
<td id="square1"></td>
<td id="square2"></td>
</tr>
<tr>
<td id="square3"></td>
<td id="square4"></td>
<td id="square5"></td>
</tr>
<tr>
<td id="square6"></td>
<td id="square7"></td>
<td id="square8"></td>
</tr>
<tbody>
</table>
I currently have a jQuery which displays 4 tables simultaneously, how could I get it to display 1 table at a time with a toggle though button?
i have displayed part of my code below. Any help would be great thanks.
<script type="text/javascript">
function call_everybody(){
display_cyclist_results_table();
display_cyclist2_results_table();
display_cyclist3_results_table();
display_cyclist4_results_table();
cyclist_heading();
}
</script>
<table class="resultsTable" align="center">
<tr><td class="tdCells"><div id="cyclist_table"></div></td>
<td class="tdCells"><div id="cyclist2_table"></div></td>
<td class="tdCells"><div id="cyclist3_table"></div></td>
<td class="tdCells"><div id="cyclist4_table"></div></td></tr>
</table>
Assuming they all have the same class, something like this should work
var $tables = $('.resultsTable');//cache table elements to avoid repeated dom searches
$tables.not(':first').hide();
$('#someButton').click(function(){
var $currTable = $tables.filter(':visible').hide(),
nextIndex = $tables.index($currTable) +1;
if(nextIndex === $tables.length){
nextIndex = 0;
}
$tables.eq(nextIndex).show();
});
Set your tables' display to none. Assume all tables have class my_table Add a class ( e.g. show ) to the one which is supposed to show, and then use jQuery to remove the class from the current and add it to the next table.
CSS:
.my_table {
display: none;
}
.my_table.show {
display: table;
}
jQuery:
var tblNum = 0;
var tblTotal = $('#table_container .my_table').length;
$("#toggle_table").on('click', function() {
$('#table_container .my_table').removeClass('show');
tblNum++;
if(tblNum >= tblTotal)
tblNum = 0;
$('#table_container .my_table').eq(tblNum).addClass('show');
});
jsfiddle DEMO
I would like to add a click event in plain JavaScript (without using jQuery) to an element like this, so I don't have an id but a class:
Yummy
If you don't have an id and don't have any selector library and you want it to work in older browsers, then it takes a bit more work. If you can put an id on it, it's quite simple. If not, it takes more code:
var links = document.getElementsByClassName("MyClass");
links[0].onclick = function() {
// put your click handling code here
// return(false) if you don't want default click behavior for the link
}
Since getElementsByClassName is not universally available in older browsers, you would need a shim to implement it when not present. Or, you could get all the links in your document with:
var links = document.getElementsByTagName("a");
and then cycle through that list until you find the one you want (perhaps checking the class name).
If you can put an ID on the link:
<a href="http://braza.com/share" id="specialLink" class="MyClass" >Yummy</a>
Then, it just takes this code:
document.getElementById("specialLink").onclick = function() {
// add code here
}
If you're going to do this regularly, the adding an event listener is a little more extensible than using the onclick property, but if you don't have any framework, then you need a function for adding an event listener that handles older versions of IE.
There can be several ways of doing this.
One is you add the click event right in the anchor
as: <a href='' onclick='yourFunct()'> Yummy </a>
The other way can be using document.getElementsByTagName('a') you can get reference to all the href's as array then you can chose that particular href and add click event to it.
like: document.getElementsByTagName('a')[0].click = function(){ }
here 0 is just symbolic if u know the exact place in array you can give that index.
The third way can be you can write a custom. document.getElementsByClassName function in javascript and use it similiarly. You can find a number of implementations of getElementsByClassName by searching google.
look at http://robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/ one of the implementation.
You simple use like below
<a href="http://braza.com/share" class="MyClass" onclick='return somefunction()'>Yummy</a>
<script>
function somefunction()
{
// do your stuff.
// return true, if you want to open the link, or false to cancel
return true;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Untitled</title>
<style type="text/css">
td { border: 1px solid #ccc; }
.findMe { color: gold; }
.youFoundMe { color: green; }
</style>
<script type="text/javascript"><!--
var aryClassElements = new Array();
function doSomething() {
aryClassElements.length = 0;
getElementsByClassName( 'findMe', document.body );
for ( var i = 0; i < aryClassElements.length; i++ ) {
aryClassElements[i].className = 'youFoundMe';
}
}
function getElementsByClassName( strClassName, obj ) {
if ( obj.className == strClassName ) {
aryClassElements[aryClassElements.length] = obj;
}
for ( var i = 0; i < obj.childNodes.length; i++ )
getElementsByClassName( strClassName, obj.childNodes[i] );
}
//--></script>
</head>
<body onload="doSomething();">
<h1>Heading 1</h1>
<div>
This code is inside my div.
<span>This code is inside a span inside the div. Link inside the span inside the div.</span>
Link inside the div.
</div>
<p>
<h2 class="findMe">My Paragraph's Heading 2</h2>
<table>
<tr>
<td class="findMe">My first cell.</td>
<td>My second cell. Link inside the cell inside the row inside the table.</td>
</tr>
</table>
</p>
</body>
</html>`