I asked a precursor to this question here:
Click link in DIV and show PHP/HTML in separate DIV
Then, after I removed the first script shown below, I was able to get the second script to work. I revised my question, but it appears to have gone silent. So I have a slightly modified question.
What is the conflict between the 2 scripts below and how can I modify them to work in tandem? Basically I want to be able to click anywhere in the DIV (“.side_items”) and have the child anchor links open in a separate DIV (“#main_content”)
Javascript:
<script type="text/javascript">
$(document).ready(function(){
$(".side_items").click(function(){
window.location=$(this).find("a").attr("href");
return false;
})
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$(".side_items a").click(function(e){
e.preventDefault();
$("#main_content").load($(this).attr("href"));
});
});
</script>
HTML: (slightly simplified)
<div id="main_content">
</div>
<div id="right_side">
<div class="side_items">
<a href="content.html">
<img src="images/examplethumb.png" /><br />
Content</a>
</div>
</div>
Both scripts work independently to achieve their individual desired result.
This will do it:
Breaking it down:
Find all the elements with a class of
side_itemsand assign a click event handler (fn) to them. Each time one of these elements is clicked,fnis executed with the context of the element. In the discarded code you were using the selector.side_items a, which meant the click handler was only bound to the links inside the div, not the div itself.Find all the links that are contained within the current element (
this), and get the value of thehrefattribute from the first element found. In the discarded code the context (this) was a link. Since our handler is now bound to the containing div, the context is also the div. To get the link you have to find it.Find the element with an id of
main_contentand load the content found athrefinto it. In the discarded code you were settinglocation.href, which causes the page to navigate away.