user3117628
user3117628

Reputation: 786

Jquery fastest way to check if item exists on page

I'm making a game where speed is important. So I'm trying to find the fastest way to check if a certain image is on the screen.

var myimages = ["Afbeeldingen/ballonBlauw.png",
            "Afbeeldingen/ballonGeel.png",
            "Afbeeldingen/ballonOranje.png",
            "Afbeeldingen/ballonRoos.png",
            "Afbeeldingen/balloonGroen.png",
            "Afbeeldingen/ballonRood.png"];

These are my images, when adding a new element it randomly selects one of these and sets them as the background image. I also have an array wich keeps track of how many of each image there are on the page:

var numberonscreen = [0,
                  0,
                  0,
                  0,
                  0,
                  0];

Each time I add an element, it adds +1 to the correct index in the array above.

What would be the best way to, when an element gets clicked, check which image it holds and set the counter for the correct index -1? Should I just check the backgroundimage and compare it to every possible one, or is there a faster way?

Thanks

Upvotes: 0

Views: 84

Answers (2)

Oriol
Oriol

Reputation: 288590

One possibility:

function handler() {
    ++numberonscreen[myimages.indexOf(this.getAttribute('src')];
}

Using native indexOf should be faster than a loop made by you.

But I suggest using an object instead:

var numberonscreen = {};
for(var i=0, l=myimages.length; i<l; ++i) // Initialize
    numberonscreen[myimages[i]] = 0;
function handler() {
    ++numberonscreen[this.getAttribute('src')];
}

This way there's no need to find the position, because you use the image as the property.

Upvotes: 1

Sani Huttunen
Sani Huttunen

Reputation: 24395

You could add a custom attribute with the index of the image and then, when you need to check which image it is, get the value of that attribute and then subtract the count on the correct index in the array. That way you don't need to enumerate any array at all.

Something like:

$('.anImage').on('click', function() {
  var index = $(this).attr('theArrayIndexOfTheImage');
  numberonscreen[index]--;
});

Upvotes: 1

Related Questions