user1234440
user1234440

Reputation: 23567

JQuery: Click Class Reaction

$(document).ready(function() {

// ............. Your jQuery Code goes here .............

    //var myArray1 = new Array( "img1", "img2" , "img3",  "img4");
    var numImg = $('#thumbNail img').length; //number of images
    var num = 0;
    var curImg = 0;


    //Prevent Image Dragging
    $("img").bind('contextmenu', function(e) {
        return false;
    }); 



    //Prevent Right Click on Mouse
    $("img").bind("mousedown", function(e){
        return false;
    });



    $(".leftThumbNail").live("click", function(){ 
        alert("HY"); 
    });


});

I am trying to have it react to when ever I click on images inside class "leftThumbnail". This class contains 2 images on the left panel. Whenever I click any of the images from that class, nothing seems to happen.

I also tried:

$(".leftThumbNail").click(function() {

        alert("HEY");

    });

In my "leftThumbNail" class I have the following:

<div class="leftThumbNail">   

<img id = "img1" src="img/thumb/image1.jpg" class = "image1Position" alt="Image 1">

<img id = "img2" src="img/thumb/image2.jpg" class = "image2Position" alt="Image 2" >

</div>

Upvotes: 0

Views: 212

Answers (1)

PlantTheIdea
PlantTheIdea

Reputation: 16359

Ok try this:

$('img').on({
    contextmenu:function(e) {
        e.preventDefault();
    },
    click:function(e){
        if(e.which === 3){
            e.preventDefault();
        }
    },
    dragstart:function(e){
        e.preventDefault();
    }
}); 

$(".leftThumbNail").on('click', function(){ 
    alert('HY'); 
});

This does the following:

  • Kills right-click by checking e.which to be specific to right-clicks
  • updates to .on(), the modern version of what you wanted to do
  • Combines your handlers for 'img' into a single .on() declaration

To consolidate it even more:

$('img').on({
    contextmenu:function(e) {
        e.preventDefault();
    },
    click:function(e){
        if(e.which === 3){
            e.preventDefault();
        } else if($(this).hasClass('leftThumbNail')){
            alert('HY');
        }
    },
    dragstart:function(e){
        e.preventDefault();
    }
}); 

No more extra handlers ... all handled in one now!

EDIT Modified to include prevention dragging (performed by using dragstart handler). Also changed return false to the more proper e.preventDefault() to allow for bubbling.

Upvotes: 2

Related Questions