I have a javascript function that someone made for me. I am kind of a noob at raw javascript. I use jquery quite often so I have been spoiled. Right now the function runs when someone clicks anywhere on the page because the document selector is used to trigger the function. I want the function to run when a specific id is clicked. I do have jquery installed as well. Anyone have any suggestions?
addEvent('#id', 'click', function(){ does not work
addEvent(document.getElementById("id"), 'click', function(){ does not work
function addEvent(obj, type, fn) {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
obj.attachEvent( 'on'+type, obj[type+fn] );
} else
obj.addEventListener( type, fn, false );
}
addEvent(document, 'click', function(){
seems to work:
http://fiddle.jshell.net/MT3ye/
The jquery way.
$("#objId").click(function(){ doSomething();});
Use document.getElementById('id') instead of document.
You should have a look at this:
https://developer.mozilla.org/en/The_DOM_and_JavaScript
how about using the
addEvent($('#id'), 'click', function(){
Would this work for you ...
$(document).ready(function ()
{
$("#element_id").click ( function(){ ... } );
...
}
Related
As of jQuery v3.0 the recommended way to bind DOM-ready-methods is $( myReadyFunction ) without any selector or delegation. Especially $(document).on('ready', myReadyFunction ) is removed in jQuery v3.
I now need to modify/override a specific, pre-existing ready-method before it is executed. I know that I can delay the execution of the ready-event by calling $.holdReady( true ) ... but how can I remove/override my old myReadyFunction ?
Existing code that should not be changed:
myReadyFunction = function() { console.info('old'); }
$( myReadyFunction );
I can add code before or after this part, here are some things I tried and did not work:
adding after
$.off( 'myReadyFunction' );
=> $.off is not a function
adding after
$(document).off( 'myReadyFunction' );
$(document).off( 'ready', 'myReadyFunction' );
=> no error messsage, but both variants don't work
myReadyFunction = function() { console.info('new'); }
$( myReadyFunction );
=> adds the new, overridden function, but does not remove the old one
I am having problems in setting the focus in instanceReady event of CKEditor 3.4.1. I have already tried the following two ways but both of them are not always working.
CKEDITOR.on('instanceReady', function(e) { CKEDITOR.instances.editor1.focus(); });
CKEDITOR.replace('editor1',
{
on :
{
instanceReady : function( ev )
{
ev.editor.focus();
}
}
} );
or maybe try this, this is much simpler:
use startupFocus : true
so your code should look like this:
CKEDITOR.replace('editor1',
{
startupFocus : true,
...
here you go my friend
CKEDITOR.replace('editor1',
{
on :
{
instanceReady : function( ev )
{
CKEDITOR.instances.editor1.focus();
}
}
} );
or
CKEDITOR.replace('editor1',
{
on :
{
instanceReady : function( ev )
{
this.focus();
}
}
} );
CKEDITOR.instances['instance-name'].on('instanceReady', function (event) {
CKEDITOR.instances['instance-name'].focus();
});
a bit late but:
CKEDITOR.replace( 'YourEditor',
{
on:
{
instanceReady : function( evt )
{
//Set the focus to your editor
CKEDITOR.instances.YourEditor.focus();
}
}
}
works fine for me.
Found here
Best way to me,
find the CKEditor instance, then
trigger focus event
The critical point is to focus instance in timeout
for (var instance in CKEDITOR.instances) {
$timeout(function() {
CKEDITOR.instances[instance].focus();
});
}
Note: I found the instance with a for loop. You may find better way to find the instance
Neither of the above answers worked for me. Here is what I did for CHROME and it works just fine:
CKEDITOR.instances['instance-name'].container.focus();
Dirty way (Make sure you read the comment under my answer):
jQuery('.cke_wysiwyg_frame').contents().find('body').focus();
Goal:
Disable links before ajax:success is received. (then i'll tell my app server thing to enable the links. I'm writing a simple board game, and don't want to be recieving multiple ajax requests before the first one is responded to, because it messes with the game logic.
<script type="text/javascript">
var disableLinks = false;
$("a").click(function(e){
if (disableLinks){
e.preventDefault();
}
});
$("a").ajaxStart(function(){
disableLinks = true;
});
$("a").ajaxStop(function(){
disableLinks = false;
});
</script>
And here are what the links look like:
<a href="/board/take_turn?id=313&x=1&y=2" data-remote="true">
<div class="ttt_square">
</div>
</a>
This is because your AJAX start and finish events never fire. Why? Because simply clicking a link isn't an AJAX request, and doesn't trigger the global AJAX events. To use the global AJAX events, you need to use an AJAX function such as .get( ), .load( ), or $.ajax( )
The code below, is mostly yours... I've just added 2 lines (which could even be reduced to 1, but I think it looks better this way)
var disableLinks = true;
$('a').click( function( e )
{
if( disableLinks )
{
e.preventDefault( );
}
var self = $(this);
$.ajax( { "url": self.attr( 'href' ) } );
} );
$('a').ajaxStart( function( )
{
disableLinks = true;
} );
$('a').ajaxStop( function( )
{
disableLinks = false;
} );
You've got a typo. e.prevenDefault(); should be e.preventDefault();
And this should be enough for disabling the default action. So you can rid of your onclick.
$("a").click(function(e){
e.preventDefault();
});
Edit:
Maybe this: jQuery - How can I temporarily disable the onclick event listener after the event has been fired?
or this: jQuery - How can I temporarily disable the onclick event listener after the event has been fired?
should solve your problem (if understand you correctly)
try this:
$('a').click(function(){
if (!this.hasClass('disabled')) {
this.addClass('disabled');
var self = this;
$.ajax({url: this.attr('href'),
complete: function(jqXHR, textStatus)
self.removeClass('disabled');
}
});
}
return false;
});
I am trying to build a media playlist that can advance the credits, play the video and change the title on thumb-hover, end of video and on next/prev click. So I need to write some functions that can then be called together. So like this:
function showBox()
{
$(this).parents('.container').find('.box').show();
};
function hideBox()
{
$(this).parents('.container').find('.box').hide();
};
$('a').hover(
function()
{
showBox();
},
function()
{
hideBox();
}
);
The problem is that $(this) does not carry through to the functions from the .hover. How do I do this?
Per #patrickdw's answer, jQuery sets the scope of a callback for an event to the DOM element upon which the event was fired. For example, see the eventObject parameter in the documentation for the click() handler.
My original answer (below) is useful when you want to create a jQuery plug-in so that you may invoke your own custom methods on jQuery objects and have the jQuery object set as this during execution. However, it is not the correct and simple answer to the original question.
// Within a plug-in, `this` is already a jQuery object, not DOM reference
$.fn.showBox = function(){ this.parents('.container').find('.box').show(); };
$.fn.hideBox = function(){ this.parents('.container').find('.box').hide(); };
$('a').hover(
function(){ $(this).showBox() },
function(){ $(this).hideBox() }
);
Edit: Or, if (as suggested) you want to add only one name to the ~global jQuery method namespace:
$.fn.myBox = function(cmd){
this.closest('.container').find('.box')[cmd]();
};
$('a').hover(
function(){ $(this).myBox('show') },
function(){ $(this).myBox('hide') }
);
Or more generally:
$.fn.myBox = function(cmd){
switch(cmd){
case 'foo':
...
break;
case 'bar':
...
break;
}
return this;
};
For more information, see the jQuery Plugin Authoring Guide.
The this will carry through if you just do:
$('a').hover(showBox,hideBox);
EDIT: To address the question in the comment, this will work for any function you assign as an event handler. Doesn't matter if it is an anonymous function or a named one.
This:
$('a').click(function() {
alert( this.tagName );
});
...is the same as:
function alertMe() {
alert( this.tagName );
}
$('a').click( alertMe );
...or this:
function alertMe() {
alert( this.tagName );
}
$('a').bind('click', alertMe );
In Javascript you can use call() or apply() to execute a function and explicitly specify this for it:
$('a').hover(
function()
{
showBox.call(this);
},
function()
{
hideBox.call(this);
}
);
The first parameter given to call() specifies the object that this will refer to in the function. Any further parameters are used as parameters in the function call.
You need to modify your code to something like this:
function showBox(elem)
{
elem.parents('.container').find('.box').show();
};
function hideBox(elem)
{
elem.parents('.container').find('.box').hide();
};
$('a').hover(
function()
{
var $this = $(this);
showBox($this);
},
function()
{
var $this = $(this);
hideBox($this);
}
);
$('a').hover(function() {
$(this).closest('.container').find('.box').show();
}, function() {
$(this).closest('.container').find('.box').hide();
});
Add parameters to showBox and hideBox so that they can accept the element, and then call showBox($(this)) and hideBox($(this)).
how can i add more behaviour to existing onclick events e.g.
if the existing object looks like
link
<script>
function sayHello(){
alert('hello');
}
function sayGoodMorning(){
alert('Good Morning');
}
</script>
how can i add more behavior to the onclick that would do also the following
alert("say hello again");
sayGoodMorning()
Best Regards,
Keshav
Here's the dirtiest way :)
<a href=".." onclick='sayHello();alert("say hello again");sayGoodMorning()'>.</a>
Here's a somewhat saner version. Wrap everything into a function:
..
JavaScript:
function sayItAll() {
sayHello();
alert("say hello again");
sayGoodMorning();
}
And here's the proper way to do it. Use the event registration model instead of relying on the onclick attribute or property.
<a id="linkId" href="...">some link</a>
JavaScript:
var link = document.getElementById("linkId");
addEvent(link, "click", sayHello);
addEvent(link, "click", function() {
alert("say hello again");
});
addEvent(link, "click", sayGoodMorning);
A cross-browser implementation of the addEvent function is given below (from scottandrew.com):
function addEvent(obj, evType, fn) {
if (obj.addEventListener) {
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent("on" + evType, fn);
return r;
} else {
alert("Handler could not be attached");
}
}
Note that if all 3 actions must be run sequentially, then you should still go ahead and wrap them in a single function. But this approach still tops the second approach, although it seems a little verbose.
var link = document.getElementById("linkId");
addEvent(link, "click", function() {
sayHello();
alert("say hello again");
sayGoodMorning();
});
Another way not mentioned is to capture the function currently assigned to the element.onclick attribute, then assign a new function that wraps the old one. A simple implementation to demonstrate would be something like
function addEvent(element, type, fn) {
var old = element['on' + type] || function() {};
element['on' + type] = function () { old(); fn(); };
}
var a = document.getElementById('a');
function sayHello(){
alert('hello');
}
function sayGoodMorning(){
alert('Good Morning');
}
addEvent(a, 'click', sayHello);
addEvent(a, 'click', sayGoodMorning);
Working Demo here
One way would be to write a third function:
link
<script>
function sayHello(){
alert('hello');
}
function sayGoodMorning(){
alert('Good Morning');
}
function foo() {
alert("say hello again");
sayGoodMorning();
}
</script>
link
would also work
Assuming a slight change to your code:
link
In plain ol' JavaScript, you'd do something like this.
var a = document.getElementById('a1');
a.onclick = function () { alert('say hello again'); a.onclick(); }
It's worth noting that jQuery makes this a bit easier. See the documentation on the click, bind, and one, for example, and in general the section on event handler attachment.