Loading a hyperlink opened in a div - in the same div - javascript

Following on my from my previous question here:
How to show a page by default on page load
I'm basically using jQuery to load links in a div - this works perfectly. However, what I want to now achieve, is when one of the pages (opened in the div) has a hyperlink, how can I open the hyperlink in the same div the page sits in now?
Let's say I have a menu:
Home | Service | About
If you click service - it loads the page inside a div - awesome.
But let's say service has a hyperlink to another page (on the same domain/setup) - currently using my code referenced in the question above, the link just opens in a new tab... This isn't the behaviour I want.
Here is the code:
$('[data-target]').click( function (e) {
$.get($(this).attr('href'), function(data){
$('#halloffame').empty();
$(data).find(".partner_body").appendTo("#halloffame");
});
e.preventDefault(); // prevent anchor from changing window.location
});
$.get( "pages/accounting-software/", function( data ) {
$('#halloffame').empty();
$(data).find(".partner_body").appendTo("#halloffame");
});
This lets me open hyper links in the div "halloffame". But it doesn't control the links in the pages - even if I use the same code on the master page:
<a data-target="#halloffame" href="pages/returns/">
If anyone can point me to where I'm going wrong, I would appreciate it :)
Have an awesome Friday, folks!

Your event listener is bound the the currently existing DOM, when you add new elements(from your ajax call) you need to either bind your event listener to the new elements aswell or use deferred event handling(eg jQuerys on).
See this answer for more details

Related

href target _blank not working properly - not opening link in new tab , javascript handling the event diferently

I'm having a problem with a href target _blank on my website.
I cannot determine why it is not opening the link in a new tab, in the section: LATEST PROJECTS > Boranito skat and others, in fact, is instead opening the link in the same tab... can someone explore my website and tell me what is happening and how to solve it? I think it does have to be something with the JS but I am not able to find the problem in the Javascript code since I am a javascript rookie and cannot understand properly what the javascript code here does...
from what I have understood due to previous google and StackOverflow research and behavior watching, it is because javascript is handling the event target _blank in a different way, in fact, javascript here is being used for website change( i mean every click you do on the menu, some divs appears, some divs disappears and it is being handled by 3 js classes), already examined the JS files, clicked right-click, used element inspector> elements> event listeners>click event to see which JS files are being triggered while clicking...
see here detailed image
as you can see, two javascript archives are executing while doing the click event:
1: `jquery.pagepiling.min.js. //// 2: animsition.js`
3: scripts.js
so apparently both javascript classes are handling the events: on click, but since I am a newbie in javascript I cannot understand how to handle this or even understand what the JS does to the website ( i am just tinkering with the given template to try to understand it and to customize it better, (and hence, make the target _blank work properly( as exposed before, while clicking the link, it opens the link in the same page) so I come here for some support of you
Here is the code snippet for you to be able to locate easily inside my website the code while using the code explorer in chrome:
<a href="project-detail.html" target="_blank" class="project-box">
<div class="project-box-inner">
<h5>Boranito<br>Skat</h5>
<div class="project-category">House Design</div>
</div>
</a>
however, will leave the javascript source files here since I am requested to give all possible details here to avoid users being in the need of accessing , here are all the 3 javascript classes handling all the template events which I don't know what they do:
(since I am not able to attach the source code of the javascript classes, I will attach a link for each js file so you could check it, thanks in forward.....
Thank you in advance.
Problem
Your script (scripts.js) on line 13 toggle animsition's feature for links: linkElement: "a.project-box". This will add an handler to every a element with a project-box class. The handler is the following code (I've commented for your understanding):
function(event) {
event.preventDefault(); // prevent the default behavior for links (prevent the behavior you want)
var $self = $(this);
var url = $self.attr('href'); // get the url of the link
if (event.which === 2 || event.metaKey || event.shiftKey || navigator.platform.toUpperCase().indexOf('WIN') !== -1 && event.ctrlKey) {
// open the link in a new tab ONLY IF I clicked on it with the middle mouse button or with Ctrl/Cmd pressed
window.open(url, '_blank');
} else {
// Else do the animation and open the link in the same tab
__.out.call(_this, $self, url);
}
}
Fix
To fix your problem, you can either
Change the way you setup Animsition, be aware that it can modify other links/behaviors in your site
Change the class of your link so it is not matched as the linkElement of your Animsition's setup. For example: remove the class of the a element (it will affect the styling) and you will see that the link opens in a new tab.
Appendix
You can find the handler's code in the devtools -> your link element -> handlers -> click.

Bootstrap remote Modal doesn't update content after first run

It comes javaScript and jQuery are beeing a big challenge for me. Like it's not enough I've started to use ajax to get over my problem - which is:
I've got some empty tables on my page. Each cell of a table has got its own id. A php-script is parsing a .xlsx file and puts the right link to the cell of my html table through javaScript code like:
document.getElementById("cellNrXY").innerHTML = "someLink";
If the link is clicked, then a Modal (Bootstrap) appears and loads the remote content (which is different depending on the clicked link).
My problem was that the remote content was cached in modal, so it worked only on first run. After closing the modal and choosing another link the previous modal appeared und didn't change to the new remote content.
I've read a lot solutions here that are based on:
$(this).removeData('bs.modal');
but had no luck with it. After some trying with different solutions one worked properly. The only problem was: when I've clicked the second time on some other link, the modal opened up with previous content and it took some seconds for the modal beeing updated. This is why I wanted to show a rotating element while the new modal content is beeing loaded. Somewhere here I've read a solution tu use ajax for this, which I've added "on luck" and ... it worked:
$("#myModal").on("show.bs.modal", function(e) {
$.ajax({
beforeSend: function() { $('#myModal')
.html('<div class="rotatingElement"></div>')
.show(); },
complete: function() { $('#myModal').html.hide(); }
});
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
The only thing is - I've no idea why this is working. Is there any chance that somebody here explain the functionality of this code to me?
if you read about the event show.bs.modal you will know that this event fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event. Learn more about Events
so what is happening is every time you open a modal this event triggers and makes an ajax call which you see like this $.ajax({ wchi has 2 options set
A pre-request callback function beforeSend
A function to be called when the request finishes complete
so whenever the modal triggeres the ajax requet is made and every time ajax request i made just before sending the request the modal html is overridden $('#myModal').html('<div class="rotatingElement"></div>').show(); and a loader is added in form of a div element with class rotatingElement and as soon as the requet completes that loader is removed via complete function $('#myModal').html.hide(); and then the e.relatedTarget property as described above gets the anchor object and the href of that anchor .../remoteContent.php is loaded in side the modal body in the following 2 steps
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));

Executing an asynchronous AJAX call when a link is clicked, and then following the link

We have a link on our page of which we want to track the usage. Currently, it's not really a link. It's a <div> tag with a data attribute containing the destination and a click handler bound to it.
When clicked, we send data to Google Analytics, and then trigger a page load with window.location = url after a short delay, so that we're sure that the data has gone through.
This approach works, but it has a major flaw: the clickable element is not actually a link, and behaves like one only in part. For example, I can't use my mouse wheel to click on it and have the link open in a separate tab (as you'd expect), or I can't right click on it and get a menu that is contextual to the link (because it's not a link).
Is there a way to use an <a> tag and get the behavior of a real link, intercept the click event, interact with Google Analytics and then follow the link normally after a small delay (to make sure the data goes through), without having to redirect ourselves and without having to lose functionality?
You can use event.preventDefault() to prevent the link from being followed:
$('a').click(function(e){
e.preventDefault();
var href = this.href;
setTimeout(function(){
window.location = href;
}, 2000)
});
With new HTML5 standards, couldn't you wrap your <div> in an <a> tag? Then you could do:
Inline:
<a href="yourawesomewebsite.com" id="gaEvent" target="_blank" onclick="_gaq.push(['_set', 'hitCallback', function(){window.location = this.href;}]); _gaq.push(['_trackEvent','category','action','label']);">
<div id ="blah"></div>
</a>
jQuery:
$('gaEvent').on('click', function(){
_gaq.push(['_set', 'hitCallback', function(){
window.location = url; // you'll still have to define this somewhere
}]);
_gaq.push(['_trackEvent','category','action','label']);
});
I totally referenced this SO post - Track event in google analytics upon clicking form submit

document.location strange behaviour? / alternative jsTree link solution?

I've build up an menu with jQuery.jsTree and every item should contain a link to a specific page. With jsTree it isnt possible to click these links due to the prevention of the standard behaviour of
<a href="index.php?content=example" ... >....</a>
links (this is actually an example of one of my links. The index.php is my standard page and just the content will be replaced). In order to fix that I found this solution:
jQuery(".tree").bind("select_node.jstree", function (e, data) {
document.location = data.rslt.obj.children("a").attr("href");
});
This solution works partly for me, which means the clicked link works but in the opened window Firebug tells me that jQuery is not defined. Is it possible that on document.location the browser "forget" the library imports (as I mentioned I stay on the index.php page and just replace the content)?
and the other question is: does anyone may know a better solution for the enabling of the links in jsTree without edit the library itself ?
thanks in advance!
If your links at first look like:
<a href="index.php?content=example" ... >....</a>
And you want to load the content into a div with ID maincontent
You can do something like:
$(".tree a").each(function(){
var $this = $(this);
$this.click(function(){
$("#maincontent").load($this.href, function(){
// this callback functions fires once load is complete,
// incase you need to do post-load operations
});
return false;
});
});
This will byposs loading the new page as a normal link would, and fetch the page via AJAX and load the returned HTML into the DIV with ID maincontent.
Code is untested, but I've done this in the past so should work as is.

Link in one div, trying to load content in a seperate div

I am using jQuery to make a website, and I want to be able to have my navigation in a separate div from my content. Also, I want to be able to have a sort of tabbed navigation system such that I can click a link in the navigation and it will load the content into the main content div. Basically, I want to do this so that I can just maintain one page with all the content, rather than a bunch of pages for each section. I have included a picture that will hopefully make my question much more clear (right click and "viw image", it's too small on this page):
example http://img402.imageshack.us/img402/1733/examplew.jpg
$('#navlink').click(function() {
$("#maindiv").load("/url.html");
return false;
});
I would encourage you to use event delegation. For instance we can use the .on method to attach a single event to the navigation pane that will listen for clicks on links:
$("#navigation").on("click", "a", function(e){
e.preventDefault();
$("#content").load( $(this).prop("href") );
});
Which works with the following markup:
<div id="navigation">
Home
Gallery
</div>
<div id="content"><!-- content will load here --></div>
Considering that you want one page with all of the content, you could simple hide all but one main div with css, and then use javascript/jQuery to show one div when a tab is clicked, and hide all of the other (main divs).
Have your navigation links change the html of your center div
<a href="#" onclick="$('#centerDiv').html('your content');">Click me<a>
if you want it to be more dynamic use ajax to load it.
and if you want to get a bit more fancy try out the Tab widget
This calls for the jQuery load() function! Go to http://remysharp.com/jquery-api/ and search for 'load' -- you just need to target the div.
By the way, this is sort of an alternative to frames or server-side includes. The only bad thing about this approach is that Search Engines won't be able to follow your links.
Using ajax with jQuery its pretty simple and totally controllable:
$('#navlink').click(function() {
$.ajax({
type: "GET",
url: 'URL_OF_THE_RESOURCE',
//(maybe you can hold this in the href attr of the anchor tag)
//in that case you can use $(this).attr('href');
dataType: "text/html", //spectating HTML back from the server
timeout: 8000, //Wait 8 second for the response
error: function() {
alert('ERROR');//case of server error or timeout give a feedback to the user
}, //end error
success: function(html) {
$('#mainDiv').html(html); //Replace the content with the new HTML
} //end succes
}); //end ajax
return false;
}); //end click
Instead of usign an ID, you could use a dummy class (like "navlink") on all those navlinks, so instead of referencing the selector to the ID, reference it to the class like:
$('.navlink').click(function(){
...
and the url parameter will be:
url: $(this).attr('href'),
That way you just set this once and all the links will get the functionality and still give support to users that don't have JS active.

Categories

Resources