Trying to write a javascript function inline: doesn't work - javascript

I tried to write down this javascript function in an inline way:
function WhichKeyPress(e) {
if (!e) {
//if the browser did not pass the event
//information to the function,
//we will have to obtain it from the
//event register
if (window.event) {
//Internet Explorer
e = window.event;
} else {
//total failure, we have no
//way of referencing the event
return;
}
}
if (typeof (e.keyCode) == 'number') {
//DOM
e = e.keyCode;
} else if (typeof (e.which) == 'number') {
//NS 4 compatible
e = e.which;
} else if (typeof (e.charCode) == 'number') {
//also NS 6+, Mozilla 0.9+
e = e.charCode;
} else {
//total failure, we have no way of obtaining the key code
return;
}
}
It became something like this:
Me.Attributes.Add("onkeydown","var evt; if(!e){ evt = window.event;}else{return;} if(typeof(evt.keyCode == 'number'){//do something}else if....."}
And it so goes on.
Needless to say it doesn't work. I've tried other inline javascript functions like this:
Me.Attributes.Add("onkeydown","if(event.keyCode == 13){return event.keyCode = 9;} ")
It works. But if i do this:
Me.Attributes.Add("onkeydown","var cod = event.keyCode; if(cod == 13){return cod = 9;})
It won't work.
Can i really write a whole javascript function inline? With variables being declared and everything else?
EDIT: I've read the link that #millimoose provided and i'm trying to use an external .js file in my dll in vs2005 but with no success. Here's wha't i've done so far:
1) Created a 'Scripts' folder with the js file in the dll solution.
2) Set the Build Action to 'EmbeddedResource'
3) Overwrote my OnPreRender method like this:
Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
Page.ClientScript.RegisterClientScriptResource(Me.GetType(), "webControlesUES.Scripts.EnterToTab.js")
Page.ClientScript.RegisterStartupScript(Me.GetType(), "EnterToTab", "teste()", True)
End Sub
4) On my Render method, i've added this:
Me.Attributes.Remove("onkeydown")
Me.Attributes.Add("onkeydown", " teste();")
If Me.TextMode = Web.UI.WebControls.TextBoxMode.MultiLine Then
Me.Attributes.Remove("onkeydown")
End If
5) Added this on my AssemblyInfo.vb
<Assembly: System.Web.UI.WebResource("webControlesUES.Scripts.EnterToTab.js", "application/x-javascript")>
6) Built the solution and added the dll for testing.
But it's not working. Am i forgetting something here?

The event object is sent as a parameter to the function also for inline code, but as you don't have any function declaration you need to pick it up from the arguments collection instead of as a named parameter.
Example:
Me.Attributes.Add("onkeydown","var e=arguments[0];if(e.keyCode == 13){ alert('enter'); }");

Related

how to terminate actions using javascript

In my image puzzle that I'm attempting to get working, I want to move the mouse cursor to a specific place if the puzzle validation fails. I've made some JavaScript code to be called when the mouse is dragged and dropped. Is there any way to cancel this mouse movement? Here's the relevant part of my code:
else if (temp == 9 && validate == false) {
if (vl == 6 || vl == 8 || vl == 9) {
var theData = theEvent.dataTransfer.getData("Text");
var theDraggedElement = document.getElementById(theData);
theEvent.target.appendChild(theDraggedElement);
theEvent.preventDefault();
temp = vl;
} else {
alert("invalied move..");
}
}
There isnt a single command if you want to support multiple browsers unfortunately. Try the following:
if (!e){
e = window.event;
}
e.stopPropagation();
e.cancelBubble = true;
the if (!e) line checks to see if e is set, as some browsers don't pass the event argument to the method.

Attempting to make enter button 'clickable'

I want to make a 'search' button clickable upon clicking enter.
This is my html:
<input type="text" runat="server" id="txtSearch" onkeypress="searchKeyPress(event);"
<input type="button" runat="server" style="padding:5px;" id="butSearch" onserverclick="butSearch_Click" value="Search" disabled/>
This is the JavaScript I am using:
function searchKeyPress(e) {
if (typeof e == 'undefined' && window.event) { e = window.event; }
if (e.keyCode == 13) {
document.getElementById("butSearch").click();
}
}
I am however getting an error
'Uncaught TypeError:Cannot call method click of nul'
Advice perhaps on why I get this error and is there a better alternative at achieving this?
are those runat="server" required? you get the error because when searchKeyPress gets called, your button doesn't exist (yet). Either it's being triggered before DOMContentLoaded, or asp.net is doing funky things with your button, keeping it out of the DOM entirely.
Also some general JavaScript tips:
function searchKeyPress(e) {
// a much cleaner "use var, or assign if not defined":
e = e || window.event;
// strict comparison:
if (e.keyCode === 13) {
// verify we have a button:
var btn = document.getElementById("butSearch");
if (btn) {
btn.click();
} else {
// btn does not exist. arbitrary code goes here
}
}
}
Try instead type="submit" inside input tag.
You can do it like that:
function searchKeyPress(e) {
e = e || window.event;
var key = e.keyCode || e.which;
if (key == 13) {
document.getElementById("butSearch").click();
}
}
In ASP.NET, ids generated client side are not those you see in your ASP.NET markup (have a look at the generated source)
You will need to invoke the ClientID property of your control to access it through javascript or jQuery.
You may try :
function searchKeyPress(e) {
if (typeof e == 'undefined' && window.event) { e = window.event; }
if (e.keyCode == 13) {
document.getElementById('<%=butSearch.ClientID%>').click();
}
}
If you understand how ASP.NET Ids are generated, you may also play with the ClientIDMode of your control, setting it to static.

JavaScript Code Explanation For: (e && e.target) || (window.event && window.event.srcElement)

I have made a JavaScript tab view of a simple HTML page.
I've added onClick functions for header tags using JavaScript via nodes.
The onClick function performs a function called showTab passing on this as a parameter.
I understand that this is [object window].
The header tag onClick functions are set as shown below:
node.onclick = function() { showTab(this); };
The showTab function is as follows:
function showTab(e)
{
var node = (e && e.target) || (window.event && window.event.srcElement);
alert(node.innerHTML);
}
Everything works fine, when i click on one of the headers, an alert appears with its innerHTML.
However, I did use a little help from Google to achieve this. And I would like some help understanding exactly what this line means:
var node = (e && e.target) || (window.event && window.event.srcElement);
I did my own research and saw it can be considered as the equivalent as sender in C#.
But I would like to know thoroughly how it works and what it is referring to and how it knows which node is calling the showTab function as there are 3 header tags that perform the same function, all without id's.
Ah, the joys of dealing with Events and browser.
The Trident Engine (Internet explorer and others based on that engine) deals with events differently than most (all?) of the other browsers.
<html>
<head>
<title>Test</title>
</head>
<body>
<button id="test_button">Click me</button>
<script>
// UGLY, UGLY, UGLY... don't really use this
var button = document.getElementById("test_button");
if (window.attachEvent) {
button.attachEvent("onclick", showTab);
} else {
button.addEventListener("click", showTab);
}
function showTab(e)
{
// Most browsers pass the event as 'e'
// Microsoft puts the event in window.event
// Either way, event will now point to the object we want.
var event = e || window.event;
// Once again, the different browsers handle the `target` property differently.
// Target should now point to the right event.
var target = event.target || event.srcElement;
alert(target.innerHTML);
}
</script>
</body>
This line:
var node = (e && e.target) || (window.event && window.event.srcElement);
is equivalent to this logic:
var node;
if (e && e.target) {
node = e.target;
} else if (window.event && window.event.srcElement) {
node = window.event.srcElement;
} else {
node = undefined;
}
The purpose of this code is to handle the fact rhat older versions of IE don't pass the event structure to an event handler. Instead, it is stored in a global variable window.event and the event target is also stored in a difference property of the event.
It is a bit more common (and I think more readable) to do something like this:
function showTab(e) {
// get the event data structure into e
e = e || window.event;
// get the source of the event
var node = e.target || e.srcElement;
alert(node.innerHTML);
}
In reality, any decent size project should use a library function for abstracting the differences in event handlers so that this browser-specific code only has to be one place in the project or use a pre-built library like jQuery for this type of thing. Here's a cross-browser event handler:
// refined add event cross browser
function addEvent(elem, event, fn) {
if (typeof elem === "string") {
elem = document.getElementById(elem);
}
function listenHandler(e) {
var ret = fn.apply(this, arguments);
if (ret === false) {
e.stopPropagation();
e.preventDefault();
}
return(ret);
}
function attachHandler() {
// older versions of IE
// set the this pointer same as addEventListener when fn is called
// make sure the event is passed to the fn also so that works the same too
// normalize the target of the event
window.event.target = window.event.srcElement;
var ret = fn.call(elem, window.event);
if (ret === false) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return(ret);
}
if (elem.addEventListener) {
elem.addEventListener(event, listenHandler, false);
} else {
elem.attachEvent("on" + event, attachHandler);
}
}
It's getting the dom element which was clicked, either e.target for standards compliant browsers or window.event.srcElement (could be e.srcElement instead for newer IE)
see: http://www.quirksmode.org/js/events_properties.html

How to open popover with keyboard shortcut? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Keyboard shortcuts with jQuery
I want to display a popover window using a shortcut key instead of clicking the icon on the toolbar.
Do you have any good idea?
Thank you for your help.
Abody97's answer tells you how to determine if a certain key combo has been pressed. If you're not sure how to get that key combo to show the popover, this is what you need. Unfortunately, Safari makes this needlessly complicated.
In the global script, you'll need a function like the following to show a popover, given its ID and the ID of the toolbar item that should show it:
function showPopover(toolbarItemId, popoverId) {
var toolbarItem = safari.extension.toolbarItems.filter(function (button) {
return button.identifier == toolbarItemId && button.browserWindow == safari.application.activeBrowserWindow;
})[0];
var popover = safari.extension.popovers.filter(function (popover) {
return popover.identifier == popoverId;
})[0];
toolbarItem.popover = popover;
toolbarItem.showPopover();
}
You'll also need code to call this function in your global script's message listener, like the following (this sample does not assume you already have a message listener in place):
safari.application.addEventListener('message', function (e) {
if (e.name == 'Show Popover') {
showPopover(e.message.toolbarItemId, e.message.popoverId);
}
}, false);
Finally, in your injected script, the function that listens for the key combo needs to call dispatchMessage, as below:
safari.self.tab.dispatchMessage('Show Popover', {
toolbarItemId : 'my_pretty_toolbar_item',
popoverId : 'my_pretty_popover'
});
(Stick that in place of showPopUp() in Abody97's code sample.)
Note: If you only have one toolbar item and one popover (and never plan to add more), then it becomes much simpler. Assuming you've already assigned the popover to the toolbar item in Extension Builder, you can just use
safari.extension.toolbarItems[0].showPopover();
in place of the call to showPopover in the global message listener, and omit the message value in the call to dispatchMessage in the injected script.
Assuming your shortcut is Ctrl + H for instance, this should do:
var ctrlDown = false;
$(document).keydown(function(e) {
if(e.keyCode == 17) ctrlDown = true;
}).keyup(function(e) {
if(e.keyCode == 17) ctrlDown = false;
});
$(document).keydown(function(e) {
if(ctrlDown && e.keyCode == 72) showPopUp(); //72 is for h
});
Here's a reference for JavaScript keyCodes: little link.
Here's a little demo: little link. (It uses Ctrl + M to avoid browser-hotkey conflicts).
I believe this could help you: http://api.jquery.com/keypress/
In the following example, you check if "return/enter" is pressed (which has the number 13).
$("#whatever").keypress(function(event) {
if( event.which == 13 ) {
alert("Return key was pressed!");
}
});

Same JavaScript for multiple instances of user control not working

I am using a user control in my website which performs the functionality of auto complete textbox. I have used JavaScript for the keydown and onfocus client events. This is the code:
<script language="JavaScript" type="text/javascript">
function TriggeredKey(e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
if (keycode == 9) {
document.getElementById("<%=pnlSearch.ClientID %>").style.visibility = 'hidden';
document.getElementById("<%=pnlSearch.ClientID %>").style.display = 'none';
}
else {
document.getElementById("<%=hdfkey.ClientID %>").value = keycode;
}
_dopostback();
}
function pasteIntoInput(el) {
var text = document.getElementById("<%=txtSearch.ClientID %>").value;
if (typeof text != "undefined" && text != "") {
el.focus();
el.value = el.value;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
var val = el.value;
var selStart = el.selectionStart;
el.value = val.slice(0, selStart) + val.slice(el.selectionEnd);
el.selectionEnd = el.selectionStart = selStart + text.length;
}
else if (typeof document.selection != "undefined") {
el.focus();
}
}
}
When I use a single instance of this control in my aspx page it works fine but when I use more than one instances in my aspx page the JavaScript of all of the controls is overwritten by the last instance of the control in my page and no other control works.
Here's how I've dealt with problems like this in the past...
A block like this goes in an external js file referenced in the control ascx.
function UserControl() {
}
UserControl.prototype = {
DoStuff : function() {
var x = this.clientID;
window.alert(this.pnlSearchClientID);
},
TriggeredKey : function(e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
if (keycode == 9) {
document.getElementById(this.pnlSearchClientID).style.visibility = 'hidden';
document.getElementById(this.pnlSearchClientID).style.display = 'none';
}
_dopostback();
},
pasteIntoInput : function() {
var text = document.getElementById(this.txtSearchClientID).value;
}
};
A block like this goes in the ascx file:
<script type="text/javascript">
function UserControl<%=this.ClientID%>() {
this.pnlSearchClientID = <%=pnlSearch.ClientID%>;
this.txtSearchClientID = <%=txtSearch.ClientID%>;
}
UserControl<%=this.ClientID%> = UserControl.prototype;
</script>
And then in the page including the user control:
<script type="text/javascript">
var inst1 = new UserControl<%=instance.ClientID %>();
inst1.DoStuff();
</script>
The idea is that you have a base class with the functionality you need, shared across all instances of the user control. Then a derived class per instance of the user control, with a new constructor setting properties for all of the instance-specific date (ie the ids of the controls composing the user control). The base class references these properties. The derived class is named using the ClientID of the user control, making it unique on the page.
I don't have access to an asp.net ATM so there are probably errors in here...
First off i would define your javascript functins in one place, perhaps the parent page or even a globally referenced file. That way you dont have the same functions rendered over and over again when you use multiple instances of your user control on a single page.
Then instead of embedding the client IDs of your pnlSearch and txtSearch controls into the JavaScript functions I would recommend passing them into the functions whenever they are called.
The way you have it set up the JavaScript functions on the last instance of your user control that is rendered will be the ones that will be invoked every time, which will cause the functions in the previously rendered user control instances to be ignored.

Categories