I've got a page in which I create some tabs.
function addTab(ticketId, name) {
$('#pageTab').append(
$('<li>'+name+'<button class="close" type="button">×</button></li>'));
$('#pageTabContent').append($('\
<div class="tab-pane" id="'+ticketId+'">\
here some more html \
</div>'));
$('#page' + ticketId).tab('show');
}
When the user wants to open the contents of the tab I open the contents with this code:
$("#pageTab").on("click", "a", function (e) {
openTab(e, this);
});
which calls this function:
function openTab(e, tabId) {
e.preventDefault();
$(tabId).tab('show');
}
I now want to call this openTab function from a different place, but I actually no idea what this e variable does or where it comes from.
Does anybody know how I can call this function and supply that e variable? All tips are welcome!
e is the context of the event. Whenever an event occurs (click, scroll, keydown etc.) you get a context object that allows you to get more information about the event. This context object is generated for you.
If you call openTab programmatically then you don't have an event. Seeing as you only preventDefault() you don't need it anyway. Consider restructuring like this:
$("#pageTab").on("click", "a", function (event) {
event.preventDefault(); // we're handling a click, so we have an event, deal with it here
openTab(this);
});
function openTab(tabId) {
$(tabId).tab('show');
}
Now you can call:
openTab($("#some_tab"));
e looks like an event to me. You don't seem to be using it except with e.preventDefault() so you can either modify the functions to not parse it or modify the openTab() function to check if it's null then you can send it a null when calling the openTab() function.
so you could do this:
function openTab(e, tabId) {
if(e!=null){e.preventDefault();}
$(tabId).tab('show');
}
then call the function like this:
openTab(null,tabId);
Or modify openTab() to look like this:
function openTab(tabId) {
$(tabId).tab('show');
}
and modify all references to openTab() as to not send the e variable so they look like this:
openTab(tabId);
Related
I am creating a function which will take in a URL and then display that URL in a light box. I am having trouble with event.preventDefault() in my function though, it says it is not a function in the error console.
I have tried explicitly passing event to the function but that simply runs the function on page load rather than when clicking
Here is my code:
// Function to display widget
function displaySportsWidget(event, iframeURL) {
// Prevent Default Event Handler
event.preventDefault();
// Build iFrame HTML
var iframe = '<iframe src="' + iframeURL + '" ></iframe>';
var html = iframe;
// Inject HTML to Generate Widget
$('.leagues-wrapper').html(html);
// Display Overlay
$('.leagues-overlay').css('display', 'block');
};
// Event handlers. Pass iFrame URL into function depending on link clicked
$('.leagues-link.league-table').on('click', displaySportsWidget('http://www.example01.com'));
$('.leagues-link.league-form').on('click', displaySportsWidget( 'http://www.example02.com'));
The code
$('.leagues-link.league-table').on('click', displaySportsWidget('http://www.example01.com'));
calls displaySportsWidget and passes its return value into on, exactly the way foo(bar()) calls bar and passes its return value into foo.
If you want to hook up an event handler, you don't call it, you just refer to it. In your case, you can do that like this:
$('.leagues-link.league-table').on('click', function(e) {
displaySportsWidget(e, 'http://www.example01.com');
});
Or if you're open to changing the order of arguments in displaySportsWidget:
function displaySportsWidget(iFrameURL, event) {
// ...
}
...then you can use Function#bind:
$('.leagues-link.league-table').on('click', displaySportsWidget.bind(null, 'http://www.example01.com'));
Function#bind creates a new function that, when called, calls the original function with a given this value (in our case, we don't need any specific one, so I'm passing null) and any arguments you gave bind, followed by any arguments that were given to the bound function. So we'll get the URL (from the bind call) followed by the event object (from when the handler is called).
Function#bind isn't on really old browsers like IE8. If you need to support them, jQuery's $.proxy does something similar:
$('.leagues-link.league-table').on('click', $.proxy(displaySportsWidget, null, 'http://www.example01.com'));
While calling your method you are not passing event as parameter along with image url .so if u pass event as parameter while calling.then your code is going to work.
Thank you
i having a very weird problem now . I has separate 2 jquery js file with my aspx file.However the pageload doesn't seem like work.
Because I'm using UpdatePanel to asynchronously call a button click event in a page.
Therefore i attach my click event within the page load method
Here is the screen shoot of my js file
Here is the sample code for modalPopup.js
function pageLoad() {
//#region Search function
$("[id$=txtSearch]").keyup(function (e) {
"[id$=txtCurrentPage2]"
$("[id$=txtCurrentPage2]").val(1)
$("[id$=txtCurrentPage]").val(1)
$("[id$=hfCurrentTxt]").val(1)
var txtSearch = $("[id$=txtSearch]").val()
var pagesize = $("[id$=ddlRowPerPage]").val()
var skip = $("[id$=txtCurrentPage2]").val()
var type = $("[id$=hfGvType]").val()
sendData(txtSearch, skip, pagesize, type);
e.preventDefault();
});
//#endregion
The sample code for the ASPX.js
function pageLoad() {
$("[id$=txtCMemberID]").bind('keyup change', function (e) {
alert("hello");
e.preventDefault();
});
}
The modalPopup.js can work very smoothly, but the ASPX.js seem like doesn't work.Anyone face this problem before.? Please guide me some idea. Thanks
Offhand, I'd wager that you are loading ASPX.js first, and then loading modalPopup.js later in the page. Both files define a global function named pageLoad. As you cannot have two separate global functions that share the same name, one is redefining the other. Rename one of the functions (it doesn't have to be called pageLoad). Example as follows:
Change ASPX.js to:
function bindKeyUpChangeHandler() {
$("[id$=txtCMemberID]").bind('keyup change', function (e) {
alert("hello");
e.preventDefault();
});
}
then call bindKeyUpChangeHandler() in addition to pageLoad().
Instead of declaring like that why not use
Sys.Application.add_load(function () {
//do stuff on page load
});
how can I add the / char at the end of the URL without force the user to write it?
I'm starting to work with SWFAddress using JavaScript and jQuery directly (without Flash) like this wonderful site.
So something like this:
http://mysite.com/section
// and after click to a specific <a ="#">button</a> get
http://mysite.com/section/#/sub-content
// instead of
http://mysite.com/section#/sub-content
I've started with this code to do it:
$(".time_dot, .time_year").click (function () {
onClickEvent (this);
});
function onClickEvent (dom) {
var timer = setTimeout (function () {
SWFAddress.setValue($(dom).parent().attr("id"));
}, 200);
// do something else
}
The setTimeout method is used to avoid the <a> button overwrite the SWFAddress.setValue method, but I don't know a way to change the URL address to url.com/content#/... to url.com/content/#/....
How can I do that?
As already said, you cannot change the URL without forcing a reload of the site. And I don't think you want that. (but it depends on how SWFAddress.setValue() actually works, if it just keeps track of the URLs internally (without changing the browsers URL) then you can do it)
But I wanted to give you an alternative for setTimeout:
$(".time_dot, .time_year").click (function (event) {
event.preventDefault();
event.stopPropagation();
onClickEvent (this);
});
function onClickEvent (dom) {
SWFAddress.setValue($(dom).parent().attr("id"));
// do something else
}
With this you prevent the click event from bubbling up and also prevent the change the default action (which would be following the link).
See jQuery event object.
You can't change the "path" part of the URL without reloading the page. So, if you're at http://mysite.com/section, you can not navigate to http://mysite.com/section/#/sub-content without reloading the page.
you mean like
$(".time_dot, .time_year").click (function () {
setTimeout (function () {
SWFAddress.setValue("/"+$(this).parent().attr("id")+"/");
}, 200);
});
function fixUrl(url) {
return url.replace(/\/?$/,'/');
}
//or
function fixUrl(url) {
return url.match(/\/$/)
? url
: url + '/';
}
I have an <input> which has an onkeydown inline event handler. In this handler, I'd like to call a function and pass a special parameter to it - the event data.
When I want to handle events (e.g. onmousemove) for the whole document, I use the following code:
document.onmousemove=function(e) {
// here I can make a good use of the 'e' variable,
// for example extract the mouse coordinates from it
}
And it works (although I don't know where the e variable - event data - comes from).
But this time I want to use the function only for the <input> mentioned above.
I need to pass the event data to the function so it can get the pressed key's code. And I want to do it in that inline event handler. I've created a function:
function myfunc (e) {
var evt=window.event?event:e;
var code=evt.keyCode;
alert (code);
}
and tried all of these methods:
<input onkeydown="myfunc(this)">
<input onkeydown="myfunc(this.onkeydown)">
<input onkeydown="myfunc(onkeydown)">
But none of them worked, the alert window kept displaying "undefined".
I looked for a solution to my problem in Google, but didn't find anything that could help me solve it.
<input onkeydown="myfunc(event)">
function myfunc (e) {
e = e || window.event;
var code = e.keyCode;
alert (code);
}
The following doesn't work... (at least not in Firefox: document.getElementById('linkid').click() is not a function)
<script type="text/javascript">
function doOnClick() {
document.getElementById('linkid').click();
//Should alert('/testlocation');
}
</script>
<a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>
You need to apply the event handler in the context of that element:
var elem = document.getElementById("linkid");
if (typeof elem.onclick == "function") {
elem.onclick.apply(elem);
}
Otherwise this would reference the context the above code is executed in.
The best way to solve this is to use Vanilla JS, but if you are already using jQuery, there´s a very easy solution:
<script type="text/javascript">
function doOnClick() {
$('#linkid').click();
}
</script>
<a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>
Tested in IE8-10, Chrome, Firefox.
To trigger an event you basically just call the event handler for that
element. Slight change from your code.
var a = document.getElementById("element");
var evnt = a["onclick"];
if (typeof(evnt) == "function") {
evnt.call(a);
}
Granted, OP stated very similarly that this didn't work, but it did for me. Based on the notes in my source, it seems it was implemented around the time, or after, OP's post. Perhaps it's more standard now.
document.getElementsByName('MyElementsName')[0].click();
In my case, my button didn't have an ID. If your element has an id, preferably use the following (untested).
document.getElementById('MyElementsId').click();
I originally tried this method and it didn't work. After Googling I came back and realized my element was by name, and didn't have an ID. Double check you're calling the right attribute.
Source: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
$("#linkid").trigger("click");
Old thread, but the question is still relevant, so...
(1) The example in your question now DOES work in Firefox. However in addition to calling the event handler (which displays an alert), it ALSO clicks on the link, causing navigation (once the alert is dismissed).
(2) To JUST call the event handler (without triggering navigation) merely replace:
document.getElementById('linkid').click();
with
document.getElementById('linkid').onclick();
Have a look at the handleEvent method
https://developer.mozilla.org/en-US/docs/Web/API/EventListener
"Raw" Javascript:
function MyObj() {
this.abc = "ABC";
}
MyObj.prototype.handleEvent = function(e) {
console.log("caught event: "+e.type);
console.log(this.abc);
}
var myObj = new MyObj();
document.querySelector("#myElement").addEventListener('click', myObj);
Now click on your element (with id "myElement") and it should print the following in the console:
caught event: click
ABC
This allows you to have an object method as event handler, and have access to all the object properties in that method.
You can't just pass a method of an object to addEventListener directly (like that: element.addEventListener('click',myObj.myMethod);) and expect myMethod to act as if I was normally called on the object. I am guessing that any function passed to addEventListener is somehow copied instead of being referenced. For example, if you pass an event listener function reference to addEventListener (in the form of a variable) then unset this reference, the event listener is still executed when events are caught.
Another (less elegant) workaround to pass a method as event listener and stil this and still have access to object properties within the event listener would be something like that:
// see above for definition of MyObj
var myObj = new MyObj();
document.querySelector("#myElement").addEventListener('click', myObj.handleEvent.bind(myObj));
If you're using this purely to reference the function in the onclick attribute, this seems like a very bad idea. Inline events are a bad idea in general.
I would suggest the following:
function addEvent(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
}
else if (elm.attachEvent) {
var r = elm.attachEvent('on' + evType, fn);
return r;
}
else {
elm['on' + evType] = fn;
}
}
handler = function(){
showHref(el);
}
showHref = function(el) {
alert(el.href);
}
var el = document.getElementById('linkid');
addEvent(el, 'click', handler);
If you want to call the same function from other javascript code, simulating a click to call the function is not the best way. Consider:
function doOnClick() {
showHref(document.getElementById('linkid'));
}
In general I would recommend against calling the event handlers 'manually'.
It's unclear what gets executed because of multiple registered
listeners
Danger to get into a recursive and infinite event-loop (click A
triggering Click B, triggering click A, etc.)
Redundant updates to the DOM
Hard to distinguish actual changes in the view caused by the user from changes made as initialisation code (which should be run only once).
Better is to figure out what exactly you want to have happen, put that in a function and call that manually AND register it as event listener.