ace21 ace21 - 1 month ago 9
Javascript Question

Javascipt Condition Statement Calling

How can I call function

CheckColour()
which performs checking of the "details" of the table? The if-else statement in
CheckColour()
will return the background colour of the element to "blue" when "details" is "M", else return pink (for the "F"). When I try to call the function as shown in the code I show, it won't work.

JavaScript Code:

//table
var table = [
"Lyn", "22", "F", 1, 1,
"May", "32", "F", 18, 1,
"Sam", "27", "F", 1, 2,
"Sham", "23", "F", 2, 2,
"Hrs", "22", "M", 13, 2
];

// function calling starts here..

for ( var i = 0; i < table.length; i += 5 ) {

var element = document.createElement( 'div' );
element.className = 'element';

var number = document.createElement( 'div' );
number.className = 'number';
number.textContent = (i/5) + 1;
element.appendChild( number );

var symbol = document.createElement( 'div' );
symbol.className = 'symbol';
symbol.textContent = table[ i ];
element.appendChild( symbol );

var details = document.createElement( 'div' );
details.className = 'details';
details.innerHTML = table[ i + 1 ] + '<br>' + table[ i + 2 ];
element.appendChild( details );
element.CheckColour(details); /*help me check this */

/*CheckColour function, help me check this too if there is any error*/
function CheckColour()
{
var element, number, symbol, details;

if(details == "M")
element.style.backgroundColor = 'rgba(0,191,255,0)';
else
element.style.backgroundColor = 'rgba(255,105,180,0)';
}

Answer Source

Your function is not a method for element, so you should not call it on element. Instead pass element to the function as well.

Also, details is a DOM element, so it cannot be equal to "M". Possibly you want to compare table[i+2] with "M".

You could do it like this:

CheckColour(element, table[i+2]);

function CheckColour(element, details) {
    element.style.backgroundColor = 
        details == "M" ? 'rgba(0,191,255,0)' : 'rgba(255,105,180,0)';
}

This uses the ternary operator (? ... :) as an alternative to an if ... else statement, because both blocks of the if perform an assignment to the same property.

Make sure to move the function definition out of the loop. It only needs to be defined once.