Reputation: 691
I know this has been asked many times here, actually I found plenty of questions, each of them with a very good answer, I also followed those answers, used the different ways I found but I still don't get it to work.
What I'm trying to do is to load an image into a div, after clicking a link, instead of redirecting to a new page.
I'm using Pure Css (http://purecss.io/) to create a menu, the menu is made of a list, and each list item has a link inside it, like so:
<div class="pure-menu pure-menu-open" id="vertical-menu">
<a class="pure-menu-heading">Models</a>
<ul id="std-menu-items">
<li class="pure-menu-heading cat">Menu heading</li>
<li><a href="path_to_image" class="model-selection">Model 1</a></li>
</ul>
</div>
In that same html file, I have another div where I want to load the image:
<div id="model-map"></div>
I've tried the following ways, using jquery, in a separate js file:
I followed the selected answer for this question, which seemed to have the best approach (Can I get the image and load via ajax into div)
$(document).ready(function(){
console.log("ready"); //this shows on console
$('.model-selection').click(function () {
console.log("clicked"); //this doesn't show after clicking
var url = $(this).attr('href'),
image = new Image();
image.src = url;
image.onload = function () {
$('#model-map').empty().append(image);
};
image.onerror = function () {
$('#model-map').empty().html('That image is not available.');
}
$('#model-map').empty().html('Loading...');
return false;
});
});
As you see, the console.log("clicked") never executes, I'll be ashamed if it's something stupid, cause it seems that the function is not handling the click event properly. I get the image of course, but in a new page (default behavior of clicking the href) and I want it to load on the div without being redirected. I hope you can help me. Thanks in advance!
The code above is working, and both answers are correct, the issue was due to some code inside tags in my html ( YUI code to create the dropdowns for the menu) and it was conflicting with my js file. I moved it to the actual js file and now it works as expected. Thanks!
Upvotes: 0
Views: 1336
Reputation: 234
You need to use event.stopPropagation();
$('.model-selection').click(function( event ) {
event.stopPropagation();
// add your code here
});
Upvotes: 2
Reputation: 21575
You just need to prevent the default behavior of moving to a new page for <a>
tags, to do this say e.preventDefault()
first:
...
$('.model-selection').click(function (e) {
e.preventDefault(); // Stops the redirect
console.log("clicked"); // Now this works
...
)};
...
Upvotes: 1