Exercise - Event basics with jQuery

by Satish Kesiboyana

HTML

<div id="container">
    
    <h1>Events</h1>
    
    <div class="wrapper">
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
        <div class="item">
            <img src="http://placehold.it/50x50.png" />
        </div>
        
    </div>
    
</div>

CSS

.item{
    float:left;
    margin:0 10px 10px 0;
}

.wrapper{
    width:250px;
}

/*.item:hover img,*/
.item.hover img{
    outline:2px solid #f90;
}

JavaScript

// Event handling with jQuery
//
// Step 1
// 
// Set up event handler(s) for div.item elements so that:
// on mouseover, the "hover" class is added AND the img "src" attributed is logged to the console
// on mouseout, the "hover" class is removed
// on click, the div is hidden (hint: hide())

var clickHandler = function(e) {
 
    $(this).hide();
    
}

var moHandler = function(e) {
  
    $(this).removeClass("hover");
    
};

var handler1 = function(e) {
   
    // this === the element handling the event (a DOM node)
    $(this).addClass('hover');
    e.target; // the source, not necessarily the same
    
    console.log($(this).find('img').attr('src'));
    
};

$("div.wrapper")
    .on('mouseover', "div.item", handler1)
    .on('mouseout', 'div.item', moHandler)
    .on('click', 'div.item', clickHandler);

// Step 2
//
// All done? Did you delegate? 
// If not, set it up so that you are delgating
// event handling to the wrapper div