Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.css() is not a function [jQuery]?

I have the following custom tag/directive :

<tile class="ng-scope gridster-item" tilevalue="1" gridster-item="tile" row="0" col = "0" ng-repeat="tile in selectedTiles"> </tile>

I've created a keyboard control where the goal is to focus on each tile ("tile" directive) in the selectedTiles array per keyboard event (shift + right arrow).

// Keyboard Tile Navigation

        //Starting pos
        var curIndex = -1

        //keyboard control
        $(document).keydown(function(event) {

        if (event.shiftKey && event.which === 39) {
                console.log("right");
                focusNext();
                }
           });

        function focusNext() {
            focusTile(+1);
        }

        function focusTile(delta) {

            var visibleTiles = $scope.selectedTiles;
            var elem = $("[gridster-item='tile']");

            curIndex = curIndex + delta;
            el = elem[curIndex];

        el.attr('tabindex', -1).focus();    
        el.css("border-color", "yellow");

        }

When I get a console log of the variable elem I get the array of tiles that appear in the dom (as is expected). The problem is when I try to add a .attr() function or a .css() function, I get the error stating these are not functions, how can i adjust?

like image 500
KO12 Avatar asked May 31 '16 04:05

KO12


2 Answers

Use $(elem[curIndex]) instead of elem[curIndex] and Try this:

.css() is method of jquery and if you want to use that method you can access element using

So it will be:

$(elem[curIndex]).css("border-color", "yellow");

Now if you want to use javascript to add style to element you can try this:

(just an example)

var myElement = document.querySelector("#superman");
myElement.style.backgroundColor = "#D93600";
like image 137
Dhara Parmar Avatar answered Sep 27 '22 15:09

Dhara Parmar


When you use like elem[curIndex], the elem (jQuery wrapper) becomes javascript object. So, you're getting such error as they are not of core javascript method but jquery.

So, you need to wrap it again with jquery:

$(elem[curIndex])//now using .css() or .attr() will not throw you errors.
like image 20
Bhojendra Rauniyar Avatar answered Sep 27 '22 16:09

Bhojendra Rauniyar