a href combi with javascript onClick - javascript

How do you make a javascript "onClick" and an html "a href" merge into one link? I want that when I click on the link the first step is the "onClick" and the second when the "onClick" is successed you redirected with the "a href" to another page.
First step: onClick="ajaxrequest('/includes/docx/boekenlijst.php', 'docgegevens')
and
Second step: a href="/Raymond_converters/docx/example.php">doc
I hope you can help me but my English is not so good. I'm sorry for that.

Using jQuery, you could try this:
<script type="text/javascript">
$(document).ready(function() {
var call_ajax = true;
$('#alink').click(function(e) {
if (call_ajax) {
e.preventDefault();
// Do AJAX
call_ajax = false;
}
}
</script>
google

It's not simple, because if you let the link do its default action i.e. redirect to its href, the AJAX request won't be triggered.
What you need to do is:
Handle the onclick and cancel the default action by having return false;
When the AJAX request is done (in its success callback method) manually redirect the user to the link href location.

Try to use jquery with a dummy callback:
<a onclick="function1()" >function</a>
function function1(someVariable,function() {
function2(someOtherVariable);
window.location="http://www.yourpage.com/";
})
function function2(someVariable, callback) {
...YUOR CODE HERE
callback();
}

Related

avascript:history.go(-window.history.length) does not work

I am doing mobile html page via phonegap
I want to redirect user to first page. So I cannot give direct link such as a href to index.html
When User click logo I want to calculate page length that he visited and use history.go.
function goBack() {
var backLength=window.history.length;
javascript:history.go(-backLength);
}
but this does not work, no error but don't redirect
Remove javascript: and wrap in script tag:
<script>
function goBack() {
var backLength=window.history.length;
history.go(-backLength);
}
</script>
Clean up code. To avoid submit, use (javascript: void 0) in href. Use proper callback
function goBack() {
console.log("Test")
var backLength= window.history.length;
history.go(-backLength);
}
I fixed it by using:
window.history.length-1

Passing a value to a Javascript function from an ActionLink with MVC3

I must call this javascript function from inside a view:
$("#addCompositionItem").click(function (carrier) {
$.mobile.loading('show');
$.ajax({
url: this.href,
cache: false,
success: function (html) {
$("#Compositions"+carrier).append(html);
$("#newServicePageContent").trigger("create");
$.mobile.loading('hide');
}
});
return false;
});
As you can see, carrier is a parameter used to load html portions in different containers. How can I pass this value from an action link?
I'm trying with:
#Html.ActionLink("Text", "ActionName", "ControllerName", new { id = "addCompositionItem", carrier="XYZ",type = "submit" })
but with no success
The way I understand what's happening is that you're using the HTML Helper to generate an anchor tag and then attaching via JavaScript to handle the click event. In your handler, you want to be able to get a piece of data from the original link.
My suggestion is to use HTML data annotations to hold the data. As you have it now, your parameters are just being encoded into the href attribute via the route parameters. If you instead move it to the html attributes and use data_carrier the framework will generate your anchor tag like the following (not the underscore-to-hyphen is automatic conversion):
#Html.ActionLink("Text", "ActionName", "ControllerName", new { /*route params*/}, new { data_carrier="..." })
Should result in something like:
<a href='...' data-carrier='...'>...</a>
Then in your JavaScript, instead of trying to get the value as a parameter, simply use the jQuery data() method or any raw JavaScript you like to access the attribute.
var carrier = $(this).data('carrier');
I think this will cover your use case.
The code snippet below was given by EndangeredMassa in this SO question. It should solve your problem.
<html>
<head>
<script type="text/javascript">
// Wait for the page to load first
window.onload = function() {
//Get a reference to the link on the page
// with an id of "mylink"
var a = document.getElementById("mylink");
//Set code to run when the link is clicked
// by assigning a function to "onclick"
a.onclick = function() {
// Your code here...
//If you don't want the link to actually
// redirect the browser to another page,
// "google.com" in our example here, then
// return false at the end of this block.
// Note that this also prevents event bubbling,
// which is probably what we want here, but won't
// always be the case.
return false;
}
}
</script>
</head>
<body>
<a id="mylink" href="http://www.google.com">linky</a>
</body>
</html>

Call javascript function on passing through link

I have a CMS which loads articles using ajax. The article is loaded through a function with some parameters. What I need is: when someone clicks a certain link, it will redirect him to the target page AND launch the function on target page. Is it possible? To be concrete, I have function loadArticle(articleID). When I access the page, there is article list. When I launch function loadArticle, it hides div with article list and shows particular article. So I need some way to call it through link, like: <a onArticlePageLoad="loadArticle(15)" href="./articles">Title</a>
Example: on page.html I have a link which points to page2.html. On click, I need to load page2.html and execute function foo in page2.html
As mentioned by ChristianF you ll need to have an identifier on your link. I have this function:
function hashtagExecute(hashtagstring,action){
if (location.hash==hashtagstring) {
action();
}
}
/*Gets: STRING -- Beggining with '#'
* FUNCTION -- The function to be executed if the above string is present in the url
Then on the link page2 with foo execution
and onload:
window.onload =function (){
hashtagExecute("#foo",foo());
hashtagExecute("#bar",bar());
... //as many different cases you want just remember to actually have those functions :)
}
You could just have a function that executes on page2.html at the bottom of the body or onload.
As people were already saying, you will need some sort of onload event on page2. But it sounds like you want that function being called to change depending on what link was clicked on page1.
Would something like this work:
page1:
page2 case A
page2 case B
page2:
<script type="text/javascript">
window.onload = function foo(){
var case = window.location.search;
if (case == "A") {
functionA();
} else {
functionB();
}
}
</script>

Calling a click event or JQuery function from the code behind VB.NET

I have a JQuery (v1.8) which handles the code after clicking a hyperlink. I would like to call that click or do anything else (as the clicking of the link would) to enforce the JQuery to run from the code behind. Any ideas?
JQuery code:
<script type="text/javascript">
jQuery(document).ready(function (){
jQuery('#lnkShowModule').toggle(
function (){
jQuery(this).html('Hide the Module');
jQuery('.hide-element').toggle();
},
function (){
jQuery(this).html('Show the Hidden Module');
jQuery('.hide-element').toggle();
}
);
});
and this is my link in the ascx control:
<a id="lnkShowModule" href="#"> show the hidden module</a>
any ideas?
add the javascript code inside a function and you can add the following code whereever you want to call the javascript function
Page.ClientScript.RegisterStartupScript(Page.GetType(), "ShowHide", "ShowHideDiv();", true);
#UPDATE 1
function ShowHideDiv(){
$(document).ready(function (){
$('#lnkShowModule').toggle(
function (){
$(this).html('Hide the Module');
$('.hide-element').toggle();
},
function (){
$(this).html('Show the Hidden Module');
$('.hide-element').toggle();
}
);
});
}
also you have to change the " a "
<a id="lnkShowModule" href="#" onclick="ShowHideDiv();"> show the hidden module</a>
If you're already posting back (as you noted in your question that you're wanting to do this from the code-behind), then you can simply set the visibility of the object in question from the code-behind as well.
If your intention is to hide a div, you can turn it into an asp:Panel (MyPanel) (which outputs a div). Then you can simply call:
MyPanel.Visible = False; ' or True
to set the visibility. No javascript/jquery required.

How do I write my script for each link I want to redirect

So I'm trying to redirect users from html links and element id tags, to other pages with javascript. I've figured out how to do one singular redirect but having trouble writing the code for multiple links heres what I have so far:
HTML:
<head>
<script type = "text/javascript" src="script2.js"></script>
</head>
<body>
NickName
Salestax
W 3 Schools
</body>
</html>
My external script so far for just one link:
window.onload = initAll;
function initAll() {
document.getElementById("redirect").onclick = initRedirect;
}
function initRedirect() {
confirm("Go to Salestax page?");
window.location="salestax.html";
return false;
{
Do I just crank out more functions and change the location value, getElementById value and the onclick value?
A nice thing about onclick events is that if you return false it'll stop the browser from going to the link defined in the HREF. If you return true it'll keep going through with the navigation. You don't need to worry about the window.location in your function if you use this method, which will simplify things a lot. So you can just do:
Salestax
I'll prompt them if they want to continue. They click yes it'll keep going as if they clicked the link normally, they click no it'll stop them from navigating away. This way you don't have to duplicate the link's HREF in both your HTML and javascript.
You could still dynamically bind this, but if you're doing it by ID I don't really see any advantage vs just defining the onclick in the HTML.
First off, unless you're trying to prevent a user from losing changes that they've made on the current page, it's not clear why you would want to create this functionality. But at any rate, here's a standard/basic approach:
window.onload = function() {
document.getElementById("redirect").onclick = redirectConfirmation("Go to Salestax page?");
document.getElementById("redirect1").onclick = redirectConfirmation("Go to Nickname?");
};
redirectConfirmation = function(msg, urlOverride) {
return function() {
if ( confirm(msg) ) {
window.location = urlOverride || this.href || "#"
}
return false;
};
};
redirectConfirmation optionally takes a second parameter which can be used to explicitly set the url that the page is redirected to; otherwise, it will default to the URL specified by the href attribute of the anchor tag being acted upon (and if all else fails, it will fail gracefully with "#").
If you're using a common library, like jQuery, you can simplify your event registration as follows:
$(function() {
$("#redirect").click( redirectConfirmation("Go to Salestax page?") );
$("#redirect1").click( redirectConfirmation("Go to Nickname?") );
});
A far better approach would be to do something like the below - that way the logic for redirecting the user stays reasonably close to the link, and so people looking at the source wont become incredibly confused when the page takes people elsewhere.
Some link
External script:
function initRedirect(message, url)
{
confirm(message);
window.location = url;
return false;
}

Categories

Resources