Adam
Adam

Reputation: 307

jQuery - firebug returns not a function

Im using jQuery and Raphael to hide/show shapes based upon which checkbox is selected but Im getting a firebug error that .show();/.hide(); are not functions when I assign variable to the checkbox id and and try to show/hide. But when I pass the shape variable name directly and show/hide it works.

Really appreciate on any help on why the first method returns an error or point me to a tutorial. Thanks!

jQuery:

var p = Raphael("test");

var square = p.rect(100, 100, 60, 60);
square.attr('fill', 'orange');
square.hide();

var circle = p.circle(250, 250, 60);
circle.attr('fill', 'yellow');
circle.show();


$("#shapePosition input[type=checkbox]").on('click', function () {
var $this = $(this);
var shapeId = $(this).attr('id');
if ($this.is(':checked')) {
    alert(shapeId);
    square.show(); //This works
    shapeId.show(); //This does not work(Error type: is not a function)
} else {
    shapeId.hide();
}
});

Fiddle:

http://jsfiddle.net/adam123/Jw9h5/30/

Upvotes: 0

Views: 128

Answers (2)

techfoobar
techfoobar

Reputation: 66663

In your code:

var shapeId = $(this).attr('id');

shapeId is a string object. And string objects do not have a .show() function.

What you can do instead is make your shapes accessible from an object and address them like below:

var p = Raphael("test");

var shapes = {};

shapes.square = p.rect(100, 100, 60, 60);
shapes.square.attr('fill', 'orange');
shapes.square.hide();

shapes.circle = p.circle(250, 250, 60);
shapes.circle.attr('fill', 'yellow');
shapes.circle.show();

$("#shapePosition input[type=checkbox]").on('click', function () {
    var $this = $(this);
    var shapeId = $(this).attr('id');
    if ($this.is(':checked')) {
        shapes[shapeId].show();
    } else {
        shapes[shapeId].hide();
    }
});

Demo: http://jsfiddle.net/Jw9h5/32/

Upvotes: 5

Dark Falcon
Dark Falcon

Reputation: 44181

As noted, shapeId is a string. You need to map that to the object you wish to display. I see the ID is the same as the name of your variable. I would propose you do the mapping this way:

var p = Raphael("test");
var shapes = {};

var square = shapes['square'] = p.rect(100, 100, 60, 60);
square.attr('fill', 'orange');
square.hide();

var circle = shapes['circle'] = p.circle(250, 250, 60);
circle.attr('fill', 'yellow');
circle.show();


$("#shapePosition input[type=checkbox]").on('click', function () {
var $this = $(this);
var shapeId = $this.attr('id');
if ($this.is(':checked')) {
    shapes[shapeId].show();
} else {
    shapes[shapeId].hide();
}
});

Upvotes: 1

Related Questions