I have some code which performs an ajax load when a link in a div element is clicked.
I now want to make the entire div clickable but not sure how to get this working with the .load. I think I know what is going wrong, but I don’t know how to fix it as I am new to jQuery – hoping someone can help.
Here is the HTML
<div class="work">
<img class="introPic" src="images/thumb.jpg" width="250" height="99" />
<h3>
<img class="arrow" src="images/arrow_open.gif" alt=">" />
<a class="titlelink" href="project2.html">Project 2</a>
</h3>
<div class="projectIntro">
<p>This is some intro text for project 2</p>
</div>
<div class="pictures"></div>
</div>
Here is the complete code block as it stands now:
$('div.work').on('click',function() {
window.location = $(this).find("a").attr("href");
return false;
var parent = $(this).parents(".work");
var content_holder = parent.children(".pictures");
if (parent.hasClass("selected_work")) {
close_other();
return;
}
close_other();
parent.addClass("selected_work");
content_holder.load(this + " #ajaxContent", function() {
});
$('.selected_work img.arrow').attr("src", "images/arrow_close.gif");
});
function close_other() {
var selected_work = $('.selected_work');
selected_work.children('.pictures').empty();
$('.selected_work img.arrow').attr("src", "images/arrow_open.gif");
selected_work.removeClass("selected_work")
}
$('div.work').click(function() {
$('html,body').animate({scrollTop: $(this).offset().top}, 500);
});
});
The first problem is that when the div is clicked, it finds the href of the anchor inside but loads it in a new window as opposed to in the current window as desired. I presume this is because of the window.location – it finds the link and goes there whereas I want it to find the link and pass it to the ajax load.
The second problem is that the variables are now wrong. While the code was correct when an anchor inside .work was clicked (and the selector was $(.work a)– .work was therefore the anchor’s parent but that is no longer the case:
I don’t need a parent any more as the parent (.work) is what I am now clicking on so I guess it becomes simply $(this) – therefore logically I want something like:
var content_holder = $(this).children(".pictures");
if $(this).hasClass("selected_work")) {
close_other();
return;
}
but that has a syntax error so it can’t be right…
Then
parent.addClass("selected_work");
should probably change to something like
$(this).addClass("selected_work");
I would really appreciate some help getting the passing of the href and the syntax right for this as I’ve been trying to get it working for 2 days now. A working example would be the icing on the cake. Many thanks!
Because
return false;rest of your code doesn’t execute. You can change hash withlocation.hash:hrefattribute/You don’t have to use
.parents()because$(this)refers to.workso final code will be: