JoeWeb
JoeWeb

Reputation: 3

Change td color by id link

I need to change the background of <td>'s content on kind of link calling.

This is the menu code:

                    <li class="dropdown">
                        <a id="FV Orders_sub" class="dropdown-toggle" data-toggle="dropdown" role="button" href="#">Inserisci Contratto<b class="caret"></b></a>
                          <ul id="FV Orders_sub" class="dropdown-menu" role="menu">
                            <li>
                               <a href="index.php?module=SalesOrder&view=Edit&parenttab=FV Orders" id="nuovocontrattoFV">Nuovo Contratto</a>
                            </li>
                            <li>
                               <a href="index.php?module=SalesOrder&view=List&viewname=50" id="nuovocontrattoBIKE">Nuovo contratto bike</a>
                            </li>
                         </ul>
                    </li>

This is the content code:

            <td class="fieldLabel {$WIDTHTYPE}" id="fieldlabel">
                {if $isReferenceField neq "reference"}<label class="muted pull-right marginRight10px">{/if}
                    {if $FIELD_MODEL->isMandatory() eq true && $isReferenceField neq "reference"} <span class="redColor">*</span> {/if}
                    {if $isReferenceField eq "reference"}
                        {assign var="REFERENCE_LIST" value=$FIELD_MODEL->getReferenceList()}
                        {assign var="REFERENCE_LIST_COUNT" value=count($REFERENCE_LIST)}
                        {if $REFERENCE_LIST_COUNT > 1}
                            {assign var="DISPLAYID" value=$FIELD_MODEL->get('fieldvalue')}
                            {assign var="REFERENCED_MODULE_STRUCT" value=$FIELD_MODEL->getUITypeModel()->getReferenceModule($DISPLAYID)}
                            {if !empty($REFERENCED_MODULE_STRUCT)}
                                {assign var="REFERENCED_MODULE_NAME" value=$REFERENCED_MODULE_STRUCT->get('name')}
                            {/if}
                            <span class="pull-right">
                                {if $FIELD_MODEL->isMandatory() eq true} <span class="redColor">*</span> {/if}
                                <select class="chzn-select referenceModulesList streched" style="width:140px;">
                                    <optgroup>
                                        {foreach key=index item=value from=$REFERENCE_LIST}
                                            <option value="{$value}" {if $value eq $REFERENCED_MODULE_NAME} selected {/if}>{vtranslate($value, $MODULE)}</option>
                                        {/foreach}
                                    </optgroup>
                                </select>
                            </span>
                        {else}
                            <label class="muted pull-right marginRight10px">{if $FIELD_MODEL->isMandatory() eq true} <span class="redColor">*</span> {/if}{vtranslate($FIELD_MODEL->get('label'), $MODULE)}</label>
                        {/if}
                    {else if $FIELD_MODEL->get('uitype') eq "83"}
                        {include file=vtemplate_path($FIELD_MODEL->getUITypeModel()->getTemplateName(),$MODULE) COUNTER=$COUNTER}
                    {else}
                        {vtranslate($FIELD_MODEL->get('label'), $MODULE)}
                    {/if}
                {if $isReferenceField neq "reference"}</label>{/if}
            </td>

I have tried to find something on web but there's nothing. I need a different background color for my td element when the user clicks it.

Upvotes: 0

Views: 2709

Answers (3)

Farmer Joe
Farmer Joe

Reputation: 6070

You can do this through javascript directly by adding an event listener to the element on the click event.

This can be done by calling the addEventListener method on the element, which you can retrieve by id by calling getElementById on the document.

HTML:

<table>
    <tr>
        <td id="td1">
            <div>
                <span>Here is my td!</span>
            </div>
        </td>
    </tr>
</table>

JS:

document.getElementById("td1").addEventListener("click",
    function() {
        this.style.background="red";                                                    
    }
);

And a working example

And a more fun example

So adapted to what looks like your td's id:

HTML:

<table>
    <tr>
        <td class="fieldLabel {$WIDTHTYPE}" id="fieldlabel">
            <!-- More elements here -->
        </td>
    </tr>
</table>

JS:

document.getElementById("fieldlabel").addEventListener("click",
    function() {
        this.style.background="red";                                                    
    }
);

EDIT:

If you want to have individual behavior for unique ids on your menu items to affect the same <td> element, then you could assign each button some click event behavior to each link and have that function either directly change the color or create a wrapper function which handles them all. I would recommend the second approach because if you wish to make changes later on it is easier to change A function then having to go through a larger portion of your code.

HTML:

<li class="dropdown">
    <a id="FV Orders_sub" class="dropdown-toggle" data-toggle="dropdown" role="button" href="#">Inserisci Contratto<b class="caret"></b></a>
        <ul id="FV Orders_sub" class="dropdown-menu" role="menu">
            <li> <a href="#index.php?module=SalesOrder&view=Edit&parenttab=FV Orders" id="nuovocontrattoFV">Nuovo Contratto</a>

            </li>
            <li> <a href="#index.php?module=SalesOrder&view=List&viewname=50" id="nuovocontrattoBIKE">Nuovo contratto bike</a>

            </li>
        </ul>
</li>
<table>
    <tr>
        <td id="td1">
            <div> <span>Here is my td!</span>

                <!-- More Stuff Here-->
            </div>
        </td>
    </tr>
</table>

JS:

document.getElementById("nuovocontrattoFV").addEventListener("click",

function () {
    switchTDBackgroundColor(this.id);
});

document.getElementById("nuovocontrattoBIKE").addEventListener("click",

function () {
    switchTDBackgroundColor(this.id);
});

function switchTDBackgroundColor(id) {
    var color = "white"; // A default setting
    if (id == "nuovocontrattoBIKE") {
        color = "blue";
    } else if (id == "nuovocontrattoFV") {
        color = "red";
    }
    document.getElementById("td1").style["background-color"] = color;
}

This way if you wanted to have more options you could simply modify the code by adding this event handler:

document.getElementById("nuovocontrattoFV").addEventListener("click",
    function () {
        switchTDBackgroundColor(this.id);
    }
);

document.getElementById("nuovocontrattoBIKE").addEventListener("click",
 function () {
        switchTDBackgroundColor(this.id);
    }
);

// ONLY HAVE TO CHANGE THE ARGUMENT FOR getElementById
document.getElementById("newListItem").addEventListener("click",
 function () {
        switchTDBackgroundColor(this.id);
    }
);

function switchTDBackgroundColor(id) {
    var color = "white"; // A default setting
    if (id == "nuovocontrattoBIKE") {
        color = "blue";
    } else if (id == "nuovocontrattoFV") {
        color = "red";
    } else if (id == "newListItem") { // Just Add this check 
        color = "yellow";             // And set to desired color
    }
    document.getElementById("fieldlabel").style["background-color"] = color;
}

Updated jsfiddle example Note: I added hashtags to the href on the links in the jsfiddle example, this was only to avoid redirects so just the color change behavior is higlighted

EDIT 2:

For a jQuery adaptation

$("#nuovocontrattoFV").click(
    function () {
        switchTDBackgroundColor($(this).attr("id"));
    }
);

$("#nuovocontrattoBIKE").click(
    function () {
        switchTDBackgroundColor($(this).attr("id"));
    }
);

// ONLY HAVE TO CHANGE THE ARGUMENT FOR getElementById
$("#newListItem").click(
    function () {
        switchTDBackgroundColor($(this).attr("id"));
    }
);

function switchTDBackgroundColor(id) {
    var color = "white"; // A default setting
    if (id == "nuovocontrattoBIKE") {
        color = "blue";
    } else if (id == "nuovocontrattoFV") {
        color = "red";
    } else if (id == "newListItem") { // Just Add this check 
        color = "yellow";             // And set to desired color
    }
    $("#fieldlabel").css("background-color",color);
}

And jsfiddle for the jquery

Upvotes: 0

Adrian
Adrian

Reputation: 737

HTML:

<td class="fieldLabel" id="fieldlabel">
    <label class="muted pull-right marginRight10px">
        <span class="redColor">*</span>
        <span class="pull-right">
            <span class="redColor">*</span>
            <select class="chzn-select referenceModulesList streched" style="width:140px;">
                <optgroup>
                    <option value=""></option>
                </optgroup>
            </select>
        </span>
        <label class="muted pull-right marginRight10px"><span class="redColor">*</span></label>
    </label>
</td>

My first issue is with the HTML structure. While it is technically feasible, nesting a <label> inside another <label> is bad practice. Or did I misinterpret the nested if statements in your example? If you can post an example of the output, rather than the template code, it might be clearer.

Placing that aside, for the moment, your best bet would be to use JavaScript to toggle a class (both for performance and for maintainability -- you should never have styles inline in your HTML, nor inline in your JavaScript unless you absolutely cannot avoid it).

CSS:

td.highlighted {
    background-color: #AAF; /* a nice, pleasing shade of purple */
}

JavaScript:

window.util = (function() {
    return {
        // class manipulation from http://www.openjs.com/scripts/dom/class_manipulation.php
        // taken from https://gist.github.com/jbergantine/1165817
        hasClass: function(ele,cls) {
            return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
        },
        addClass: function(ele,cls) {
            if (!this.hasClass(ele,cls)) ele.className += " "+cls;
        },
        removeClass: function(ele,cls) {
            if (this.hasClass(ele,cls)) {
                var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
                ele.className=ele.className.replace(reg,' ');
            }
        }
    };
})();

var tdClick = function(event) {
    var util = window.util;
    // if clicked element is a highlightable <td>
    if (util.hasClass(event.toElement, "clickToHighlight")) {
        // toggle class
        if (util.hasClass(event.toElement, "highlighted")) {
            util.removeClass(event.toElement, "highlighted");
        } else {
            util.addClass(event.toElement, "highlighted");
        }
    }
}

document.getElementById("tableId").addEventListener("click", tdClick);

JSFIDDLE

...or if you prefer jQuery:

$("#tableId").on("click", ".clickToHighlight", function(e) {
    var $this = $(this);

    if ($this.is(".clickToHighlight")) {
        $this.toggleClass("highlighted");
    }
});

JSFIDDLE

You'll notice I'm attaching the event handler to the table itself. This is because, with a large enough table, having an event attached directly to each element could cause performance issues, and if the table can be updated via AJAX, then you have yet another problem of needing to append new event handlers to each newly-generated table cell. The technique I'm using is called "event delegation," wherein we delegate the event listener to a parent element, where it will process every click event and filter out which ones are important and act on them, as opposed to having dozens or hundreds of individual listeners.

Upvotes: 1

StephenH
StephenH

Reputation: 1126

You will need to use the Javascript onclick Event to trigger the change. In your Javascript function, you can pass the element into the function.

HTML

<td class="fieldLabel {$WIDTHTYPE}" id="fieldlabel" onclick="changeTD(this);">

Javascript

function changeTD(x)
{
    x.style.color="red";
}

or...

function changeTD(x)
{
    x.style.color="#00ff00";
}

or...

function changeTD(x)
{
    x.style.color="rgb(0,0,255)";
}

onclick Event

Pass element to function

CSS Color

Change Style with Javascript

Upvotes: 0

Related Questions