Why isn't this preventing default links? - javascript

I'm trying to prevent default links, because I'm dynamically loading pages into divs with jQuery, and the href for each like is just the name before the page (e.g. href=home, and fixing to load to home.php in code below).
//initialize home page as active on load up and deactivate link
var activePage = $('a[href$="home"]');
var activePageHref = activePage.attr('href');
activePage.attr('href', '#');
$('a').click(function(e) {
e.preventDefault();
//set the page clicked on
var page = $(this).attr('href');
//check to see if there are any extras to url for php
var pageCheck = page.split('?');
//sort page type
if (pageType == null) {
//dynamically load the page in div bodycontent
$('#bodycontent').load(page + '.php');
} else {
$('#bodycontent').load(page + '.php?' + pageCheck[1]);
}
//pull up last disabled link for navigation
var setOld = $('a[href$="' + activePageHref + '"]');
setOld.attr('href', '' + activePageHref + '');
//set the new disabled link for navigation
activePage = page;
//make link inactive
$(this).attr('href', '#');
});
It was ok with return false at the end until I added MORE things I needed to happen in the click event function, but to be exact, this part:
//pull up last disabled link for navigation
var setOld = $('a[href$="' + activePageHref + '"]');
setOld.attr('href', '' + activePageHref + '');
//set the new disabled link for navigation
activePage = page;
//make link inactive
$(this).attr('href', '#');
Now the e.preventDefault();, which is from what I understand the correct way of doing what I need to happen, is stopping the entire thing from firing on any links. I'm stuck. I just need to stop default action, and use the function I've built with the extras at the end I've added to make my navigation pretty.
Also to add, I do have a hover function tied to the ul of this navigation, but didn't include it as it shouldn't causing an issue, but I can put it in here if needed. That is the only other thing in this document ready function.

Updated:
Since you change the disabled link's href initially, the attribute-contains selector won't be able to find it again later on to activate it. I would suggest doing this a little bit differently.
You can capture the entire 'disabled link' functionality by using classes. If you add a class to links which should be "disabled" you can prevent the browser from following only links with that specified class.
When you click on an "enabled link", follow it then make it disabled. Then, enable all other links.
$('a').click(function() {
$(this).addClass('disabledLink');
$('a').not(this).removeClass('disabledLink');
}
Then, set up an event listener for the whole document which prevents the default action on links with a certain class.
$(document).on('click', 'a.disabledLink', function(e) {
e.preventDefault();
}
This should achieve what you want as is (i.e. it would replace your entire 'click' handler above). Note with this the href will never be changed to '#'.
Otherwise: just cache the link itself along with its href
//pull up last disabled link for navigation
activePage.attr('href', '' + activePageHref + '');
//set the new disabled link for navigation
activePage = $(this);
activePageHref = $(this).attr('href');
//make link inactive
$(this).attr('href', '#');
You have a syntax error which is causing the JS engine to halt:
//pull up last disabled link for navigation
$('a[href$="' + activePageHref + '"]').attr('href', '' + activePageHref + '');
//set the new disabled link for navigation
activePage = page.attr('href');
/* THIS HERE RETURNS A STRING SO YOU CHANGE activePage to a string. */
// Should probably be:
activePageHref = page.attr('href');
//make link inactive
activePage.attr('href', '#');
Befor you invoke this method you set activePage to be a string, which has no method .attr() so it throws an error and execution of the function stops.

Related

window.location.replace going into infinite loop. How to change url in javascript

I want to change the url on scroll horizontally.
Used window.location.replace window.location.assignevent.preventDefault();
http://igv.org/web/examples/events/track-url.html#/locus/chr1:155,167,355-155,190,548 on scrolling, url changes to this
http://igv.org/web/examples/events/track-url.html#/locus/chr1:155,168,900-155,192,093
But it reloading or refreshing continuously
Used below steps
var myIgvBrowser = igv.createBrowser(div,options);
myIgvBrowser.on('locuschange', function (referenceFrame, label) {
var change_url = HASH_PREFIX + label + id + id_val;
alert(change_url);
// if (window.location.href !== redirectLocation) {
window.location.replace(change_url);
// return false;
});
&
var myIgvBrowser = igv.createBrowser(div,options);
myIgvBrowser.on('locuschange', function (referenceFrame, label, event) {
var change_url = HASH_PREFIX + label + id + id_val;
window.location.replace(change_url);
event.preventDefault();
});
alert(change_url); - working
on scrolling, alert shows changed positions but window.location.replace not working
How to solve this and if any help thanks guys in advance
Seems like you are doing a window.location.replace every time your page loads up and you don't check if you really need to do window.location.replace or not.
You need to check if location.replace is really required or not at first place, since you are only changing the hash value, replace it with
window.location.hash = label + id + id_val;

How to get anchor text in a Session variable?

I am working on a project in which i have linked many pdf files in the master page.On clicking the anchor the page redirected to the specified page and displays pdf in iframe.Now i want the text in anchor tag to be displayed on the page where pdf is opened.
Consider I have an anchor which looks like this :
News Letter
Now i want the text " News letter" to be shown on the redirected page.
I think i could this by saving the text in session variable.But How can I save the anchor text in Session variable without specifying any id or class to the anchor tag? Can anyone help me please ?
You probably looking for QueryString instead of session, You are already passing path in QueryString, also pass the anchor text. You need to add this to url while you are creating the anchor tag.
News Letter
On server side
lblForAnchor.Text = Request.QueryString["aText"].ToString();
Edit you can not change the query string when it is created then you can change it when it is loaded in DOM in document.ready. Assign a class to your anchors to be specific.
$( 'a.someclass' ).attr( 'href', function(index, value) {
return value + '&aText=' + $(this).text();
});
Other way to do this on click of anchor.
$( 'a.someclass' ),click(function(event) {
window.location.href = this.href + '&aText=' + $(this).text();
});
You can try this
$("a").click(function (e) {
if($(this).attr("href").match(".pdf$"))
{
window.location.href = $(this).attr("href") + "&title=" + $(this).text();
e.preventDefault();
}
});
On server side in "Main_Content.aspx"
strTitle = Request.QueryString["title"];
You could Write the content dynamically with javascript:
News Letter
Javascript:
<script language="javascript">
function openWin(t,u) {
docstring='<iframe src='+u+'></iframe>';
win = window.open();
newdoc=win.document;
newdoc.writeln(t);
newdoc.write(docstring);
newdoc.close();
}
var elements = document.getElementsByTagName('a');
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onclick = function () {
var theAnchor = elements[i].innerHTML;
var theHref = elements[i].href;
if(theHref.match(/\.pdf/)){
openWin(theAnchor,theHref);
}
}
</script>
Or call a different address with URL and test as parameters and generate the doc on the server side.
I'm not sure how this will behave with the link click but it might be worth a shot.
links should not have to be modified.

jquery trigger on('click') of dynamically loaded content

I'm writing a webpage that uses an image map. The image and map are loaded dynamically. If I click on the area element new content is loaded. Also the url changes its hash (eg. index.php#somepage). I have three layers of pages, the main layer (homepage) has it's own image with a map (index.php), the second layer offers a new image + map (index.php#somepage) and the third layer opens an overlay on the second layer, therefore changing the hash (index.php#somepage_somesubpage).
I now want to be able to send someone a link to index.php#somepage_somesubpage. So I slice the hash and trigger the click-method of the imagemap on the first level to load index.php#somepage when the page is loaded. I added a callback to that, calling the desired click-method of the now updated imagemap. This does not work for some reason I can't figure out. I am able to open index.php#somepage, but when I enter index.php#somepage_somesubpage I end up getting the same result.
Here is the code of $(document).ready:
var cont = $('#content');
$( document ).ready(function() {
cont.load('pages/home.php', function(responseTxt,statusTxt,xhr){
if(statusTxt=='error')
{
cont.load('404.php');
}
lineparser('#content'); //Perform some fancy stuff on the page
var hash = location.hash.replace('#', '');
if (hash != ''){
if(hash.indexOf('_') > 0)
{
//open page with content
$('area[href~="#' + hash.slice(0, hash.indexOf('_')) + '"]').first().trigger("click", function(){
$('area[href~="#' + hash + '"]').first().trigger("click");
});
}
else{
//open menu page
$('area[href~="#' + hash + '"]').first().trigger("click");
}
}
});
});
I solved the problem like this:
$('area[href~="#' + hash.slice(0, hash.indexOf('_')) + '"]').first().trigger("click", [hash]);
Then I added the following:
$(document.body).on('click', "map area", function(e, schachteln){
...
if(schachteln){
$('area[href~="#' + schachteln + '"]').first().trigger("click");
}
}

have only one class name append to the end of href of an anchor tag?

var myClass;
jQuery(".option-set a").click(function() {
myClass = jQuery(this).attr("class");
jQuery("a.perma").each(function() {
var _href = jQuery(this).attr("href");
jQuery(this).attr("href", _href + "#filter=." + myClass);
});
});
Im using this code to append the class name of the filters to the end of the permalink for each thumbnail here
The issue Im running into now is that the class keeps getting assigned to the end of the permalink with each click so if I click on print then web then photography the url of the permalink would appear as: /#filter=.print#filter=.web#filter=.photography which still works, however it would be great if for the sake of tidiness it only displayed the last one.
Also once a thumbnail is clicked and the next page is loaded, I need the thumbnails to maintain the current permalink of the filter selected. Any ideas would be appreciated. I just cant seem to figure this out. I truly appreciate the help!!
call it just once not on every click...
jQuery(document).ready(function() {
myClass = jQuery('.option-set a').attr("class");
jQuery("a.perma").each(function() {
var _href = jQuery(this).attr("href");
jQuery(this).attr("href", _href + "#filter=." + myClass);
});
jQuery(".option-set a").click(function() {...});
});
This modification should check if current class filter is not present.
jQuery("a.perma").each(function() {
var _href = jQuery(this).attr("href"),
newHref = _href.indexOf(myClass) === -1 ? _href + "#filter=." + myClass : _href;
jQuery(this).attr("href", newHref);
});
});
And to maintain filtered thumbnail urls on next page load you need to work with server and parse what parameters it passes or use Web storage to save current filtered path and set thumbnail hrefs accordingly on document load.

How can I change the href of an anchor after it has been clicked?

I have a page that pulls in data via AJAX. As well as this I have a link to download said data as a CSV file.
The problem I have is that upon I need to pass some parameters along with the click event so that the server can return the correct CSV file.
Without any processing the link looks like this:
Download Target Reports
This then fires off an ASP.NET MVC Controller action that returns the CSV. What I want to do though is pass two parameters along in the query string. Initially I thought that I could intercept the click event and add data to the query string like so:
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
var anchor = $(this);
var link = anchor.attr('href');
link = link + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
anchor.attr('href', link);
It would seem that changing the href at this stage will not update the link in time and the URL will be as it was when it hits the server?
Is it possible to change a URL after it has been clicked or do I need to look at another method?
Thanks
You could redirect the window yourself, like this:
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
window.location.href = this.href + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
return false; //prevent default going-to-href behavior
Or, whatever is updating those hidden fields, update the link then instead of when it's clicked, for example:
$("#someField").change(function() {
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
$("a.black").attr("href", function() {
return "/manager/TargetResults.csv" + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
});
});
The main difference is this still allows normal click behavior to work, ctrl+click, etc.
Just rounding out your options, you could put a span inside the link:
<span>Download Target Reports</span>
...and then hook the click event on the span, which will happen before the click on the link.
you can make javascript redirect here:-
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
var anchor = $(this);
var link = anchor.attr('href');
link = link + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
anchor.attr('href', link);
location.href=link;
ya someone can disable js but your code is completely based on js.
Thanks
Without having a href, the click will reload the current page, so you need something like this:
jhhghj
Or prevent the scroll like this:
jhhghj
Or return false in your f1 function and:
jhhghj
....or, the unobtrusive way:
jhg
jhhghj
<script type="text/javascript">
document.getElementById("myLink").onclick = function() {
document.getElementById("abc").href="xyz.php"; `enter code here`
return false;
};
</script>

Categories

Resources