Search code examples
javascriptbackground-imageonmouseover

Change div background specific for the div


I need help making a script for my project.

This is how the code looks like.

var thumbnails = document.getElementsByClassName("thumbnail");
var thumbnails_lenght = thumbnails.length;

for(var i=0; i<thumbnails_lenght; i++) {
	thumbnails[i].onmouseover = function() {
		//The problem part
	};
	thumbnails[i].onmouseout = function(){
		
	};
}
*{
	margin: 0 auto;
	font-family: sans-serif;
}
.item{
	width: 240px;
	height: 240px;
	margin: 5px;
	background: #EEE;
}
.thumbnail{
	width: 240px;
	height: 200px;
	background: #DDD;
}
.description{
	width: 240px;
	height: 40px;
	line-height: 20px;
	text-align: center;
	font-size: 14px;
}
<div class="item">
	<div class="thumbnail" id="1"></div>
	<div class="description">test</div>
</div>

I need to make it so when hover over div with specific class thumbnail to get the id of the thumbnail, every thumbnail div will have it's id and i need to get that number.


Solution

  • var thumbnails = document.getElementsByClassName("thumbnail");
    var thumbnails_lenght = thumbnails.length;
    
    for(var i=0; i<thumbnails_lenght; i++) {
    	thumbnails[i].onmouseover = function(event) {
    		// You can get the id from the event passed to the handler:
            alert('The id is: ' + event.target.id);
    	};
    	thumbnails[i].onmouseout = function(){
    		
    	};
    }
    *{
    	margin: 0 auto;
    	font-family: sans-serif;
    }
    .item{
    	width: 240px;
    	height: 240px;
    	margin: 5px;
    	background: #EEE;
      float: left;
    }
    .thumbnail{
    	width: 240px;
    	height: 200px;
    	background: #DDD;
    }
    .description{
    	width: 240px;
    	height: 40px;
    	line-height: 20px;
    	text-align: center;
    	font-size: 14px;
    }
    <div class="item">
    	<div class="thumbnail" id="1"></div>
    	<div class="description">test 1</div>
    </div>
    <div class="item">
    	<div class="thumbnail" id="2"></div>
    	<div class="description">test 2</div>
    </div>
    <div class="item">
    	<div class="thumbnail" id="3"></div>
    	<div class="description">test 3</div>
    </div>

    Your event handler will receive an event object. That object will have a "target" property which is the element that triggered the event. You can get the ID from event.target. I've modified your code to alert the ID.