I have a file called main.html that contains several div's each with 2 classes:
1st is their specific class 2nd is a class called menu-item which I use to determine if an event will triggered when clicked.
The file contains this:
<div id="load-here">
</div>
<div class="item-1 menu-item">
click this
</div>
I also have a gallery.html file which I want to be loaded into the main.html file in the #load-here div, and let's say it contains this:
<div class="menu-item>
<!-- some image here -->
<img href="img/1.jpg />
</div>
The script I have is this:
$(document).ready(function() {
$( "div" ).click(function() {
if ( $( this ).hasClass( "menu-item" ) ) {
$("#load-here").load("gallery.html" + this.class);
}
});
});
The problem: It's not working. I've tried various changes. Somehow it's not loading into the #load-here div
Take a look at this: http://api.jquery.com/load/
$( "#b" ).load( "article.html #target" );
There seem to several issues:
$( "div" ).click(function() ... you are registering the click on all divs available. This might cause strange behaviour. Better use: $("div.menu-item").click( ...this is cheating you, as the context of the call may be different. Things are more clear if you handle the event as explicit parameter and check the event target..class. But, in the DOM there is a .className. Better try to use the jQuery $().attr('class'). Also, the parameter needs a separator: gallery.html?parameterTo sum it up, here my suggestion:
$("div.menu-item").click( function(event) {
var jqTarget = $(event.target).closest('.menu-item');
if ( jqTarget.hasClass( "menu-item" ) ) {
$("#load-here").load("gallery.html" + "?" + this.class);
}
});
closest() will attempt to find the closest matching element, in case the click target was not on the div itself, but rather a child img or else. So, the condition in the suggestion should be used to find out about more specific about which menu item was clicked: if ( jqTarget.hasClass( "that-specific-item" ) ...