Okay so I want to click an item, then have that item become unclickable, and not execute the jQuery attached to it. I am currently using this
$(clicked_id).prop('disabled', true);
However that is not working.
Any help is much appreciated!
EDIT:
This is the HTML:
<img src="imgs/card.jpg" id="card0" name="card0" onclick="getCard(this.id); ">
disabled is only for disabling input elements (and it doesn't change the clickability of the object -- just that the default animation isn't executed).
To make it so that the click event is removed from an object, use .off()
$(clicked_id).off('click')
But this only works if the onclick was added via jquery
Instead, you may do this:
$(clicked_id)[0].onclick=false
Since your handler is assigned as an attribute, you can just nullify the property for that event handler.
document.getElementById(clicked_id).onclick = null;
just make sure you don't have a leading # on the ID.
Or us jQuery like this:
$(clicked_id).prop("onclick", null);
Or you can pass the element itself instead of passing the ID.
<img src="imgs/card.jpg" id="card0" name="card0" onclick="getCard(this); ">
And then change your function so that it receives the element instead of the ID of the element. Once you do that, you can access the element directly.
elem.onclick = null;
There is another solution:
function getCard(objId){
if( !($('#'+objId).attr('used') == '1') )
{
alert('Click is working for '+objId);
// do something
$('#'+objId).attr('used', '1');
}
}
Here is a working example:
http://jsfiddle.net/HqHut/
Related
I have an element with a a script for a mouseover to show an image. I can't change the HTML, so is it possible to disable the javascript in the link, but still keep the link for the href intact? I cant use the id of the a element since it isn't unique.
HTML:
<div class="container">
<a id="a211094" onmouseout="etim();" onmouseover="stim('/imgs/7c24b548-4f4c-418e-ad4f-53c73cf52ace/250/250',event,this.id);" href="/products/Computers/Desktops/Acer/Acer-Aspire-TC-705W-Towermodel-1-x-Core-i3-41?prodid=211094"><img src="" alt="">
</a>
</div>
if you want to make all ancher tag or you can give class for those anchor tags on which you want to perform this and instead of $( "a" ) write $( ".myClass" )
$( "a" ).each(function( index ) {
$( this ).removeAttr("onmouseout");
$( this ).removeAttr("onmouseover");
});
use can use attr("disabled", "disable"); to disable it
Overwriting the JavaScript:
document.getElementById("a211094").onmouseover = null
document.getElementById("a211094").onmouseout = null
document.getElementById("a211094").removeAttribute("onmouseout");
document.getElementById("a211094").removeAttribute("onmouseover");
If you can consistently access and control the containing element you could try a slightly left-field approach using an onmouseover event on the container.
There's a function called setCapture() which you can call during a mouse event to "capture" all mouse events of that kind for the element it's called against, until a mouseup event or releaseCapture() is called. So you could do something like the following:
jQuery(document).ready(function() {
$container = jQuery("#<yourcontainerid>");
$container.on("mouseover", function(e) {
if (e.target.setCapture) e.target.setCapture(true);
});
$container.on("mouseout", function() {
document.releaseCapture();
});
});
The (true) argument is important (I think, without testing) as it prevents any descendent events firing, which is what you want here.
The mouseout function will then release the capture when it leaves the area of the container.
Will this work? can't say for sure, I haven't tested it in your exact case, but in theory it should!
UPDATE: you can use ".container" rather than "#yourcontainerid" in the JQuery if you so wish to enable this for everything of class container.
I'm having trouble with a jQuery/Angular function being executed on click.
<a ng-click="like()" href="#" class="like like--yes"></a>
Basically, when a click occurs on a like button, I want to toggle the like--yes and the like--no classes. I've inspected the DOM while clicking, and once it has been set to like--no, it refuses to change back.
$scope.like = function() {
$('.like--no').toggleClass('like--no like--yes');
$('.like--yes').toggleClass('like--yes like--no');
}
I need two different functions so to speak, as I'm adding different animations depending on whether it's a like/unlike.
Any idea where I'm going wrong? There's more to it, but I've stripped some of the unnecessary code out for clarity.
Thanks.
I see that you are using AngularJS so instead of using jQuery, why not use ngClass?
Like this:
<a ng-click="toggleLike()" ng-class="{'like--yes': like, 'like--no': !like}">Hello World!</a>
Plunkr
It seems there is a logical issue
$scope.like = function() {
$('.like--no').toggleClass('like--no like--yes');
$('.like--yes').toggleClass('like--yes like--no');
}
Case:- first line changes like--no to like--yes and after that second line changes like--yes to like-- no again.
You should try .hasClass() function to check whether element has class then use toggle.
It seems like the second line is overwritting the first one.
It sets the class to like--yes and the second line catches the like--yes and set it to like--no everytime.
Try something like:
$scope.like = function() {
if( $('.like').hasClass( 'like--yes' ) ) {
$('.like').removeClass( 'like--yes' );
$('.like').addClass( 'like--no' );
} else {
$('.like').removeClass('like--no');
$('.like').addClass('like--yes');
}
}
Maybe you need change $('.link') to $(this) to get the actually clicked element.
It's generally frown upon to deal with DOM jQuery-style inside an Angular's controller, which is what you attempted to do and the other answers suggested.
Just have a variable that reflects the like state (you can set it directly in the View or inside the $scope.like() function and use ng-class to toggle the class:
<a ng-click="like=!like" href="#" ng-class="like ? 'like--yes':'like--no'"></a>
try this
$('.like').on('click',function(e){
e.preventDefault();
$(this).toggleClass('like--no like--yes');
if($(this).text() == 'like'){
$(this).text('unlike');
}else{
$(this).text('like');
}
});
and html
like
JSFIDDLE
I have a div tag in my form without id property. I need to set an on-click event on this div tag.
My HTML code:
<div class="drill_cursor" >
....
</div>
I don't want to add an id property to my div tag.
How can I add an on-click event on this tag using JavaScript?
Pure JavaScript
document.getElementsByClassName('drill_cursor')[0]
.addEventListener('click', function (event) {
// do something
});
jQuery
$(".drill_cursor").click(function(){
//do something
});
Try this:
var div = document.getElementsByClassName('drill_cursor')[0];
div.addEventListener('click', function (event) {
alert('Hi!');
});
Just add the onclick-attribute:
<div class="drill_cursor" onclick='alert("youClickedMe!");'>
....
</div>
It's javascript, but it's automatically bound using an html-attribute instead of manually binding it within <script> tags - maybe it does what you want.
While it might be good enough for very small projects or test pages, you should definitly consider using addEventListener (as pointed out by other answers), if you expect the code to grow and stay maintainable.
Recommend you to use Id, as Id is associated to only one element while class name may link to more than one element causing confusion to add event to element.
try if you really want to use class:
document.getElementsByClassName('drill_cursor')[0].onclick = function(){alert('1');};
or you may assign function in html itself:
<div class="drill_cursor" onclick='alert("1");'>
</div>
the document class selector:
document.getElementsByClassName('drill_cursor')[0].addEventListener('click',function(){},false)
also the document query selector https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
document.querySelector(".drill_cursor").addEventListener('click',function(){},false)
Separate function to make adding event handlers much easier.
function addListener(event, obj, fn) {
if (obj.addEventListener) {
obj.addEventListener(event, fn, false); // modern browsers
} else {
obj.attachEvent("on"+event, fn); // older versions of IE
}
}
element = document.getElementsByClassName('drill_cursor')[0];
addListener('click', element, function () {
// Do stuff
});
I have a link that looks like this:
<a id="mylink" onclick="deleteHike( 3 );" href="javascript:void(0);">Yes</a>
It is able to call this JavaScript:
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( hike_id )
{
// Somecode her
// But when I try to use the hike_id it displays as [object MouseEvent]
}
}
But the value that comes in is [object MouseEvent], not the number that I was expecting. Any idea why this happens and how to fix this? :)
Thanks!
You are trying to assign the function to your link in two different and conflicting ways.
Using the eval-ed function string, onclick = "function(value)", works but is deprecated.
The other way of binding the click handler in the onload event works too, but if you want a particular value to be passed, you'll have to change your script a bit because the value as given in the initial onclick is completely lost when you set the onclick to a new function.
To make your current method work, you don't need an onload handler at all. You just need this:
function deleteHike(hike_id) {
// Some code here
}
To do it the second way, which I recommend, it would look like this:
<a id="mylink" href="javascript:void(0);">Yes</a>
with this script:
function deleteHike(e, hike_id) {
// Some code here
// e refers to the event object which you can do nifty things with like
// - learn the actual clicked element if it was a parent or child of the `this` element
// - stop the event from bubbling up to parent items
// - stop the event from being captured by child items
// (I may have these last two switched)
}
function getCall(fn, param) {
return function(e) {
e = e || window.event;
e.preventDefault(); // this might let you use real URLs instead of void(0)
fn(e, param);
};
}
window.onload = function() {
var a = document.getElementById("mylink");
a.onclick = getCall(deleteHike, 3);
};
The parameter of a DOM event function is the event object (in Firefox and other standards-compliant browsers). It is nothing in IE (thus the need to also grab window.event). I added a little helper function for you that creates a closure around your parameter value. You could do that each time yourself but it would be a pain. The important part is that getCall is a function that returns a function, and it is this returned function that gets called when you click on the element.
Finally, I recommend strongly that instead of all this, you use a library such as jQuery because it solves all sorts of problems for you and you don't have to know crazy JavaScript that takes much expertise to get just right, problems such as:
Having multiple handlers for a single event
Running JavaScript as soon as possible before the onload event fires with the simulated event ready. For example, maybe an image is still downloading but you want to put the focus on a control before the user tries to use the page, you can't do that with onload and it is a really hard problem to solve cross-browser.
Dealing with how the event object is being passed
Figuring out all the different ways that browsers handle things like event propagation and getting the clicked item and so on.
Note: in your click handler you can just use the this event which will have the clicked element in it. This could be really powerful for you, because instead of having to encode which item it was in the JavaScript for each element's onclick event, you can simply bind the same handler to all your items and get its value from the element. This is better because it lets you encode the information about the element only in the element, rather than in the element and the JavaScript.
You should just be able to declare the function like this (no need to assign on window.onload):
function deleteHike(hike_id)
{
// Somecode her
// But when I try to use the hike_id it displays as [object MouseEvent]
}
The first parameter in javascript event is the event itself. If you need a reference back to the "a" tag you could use the this variable because the scope is now the "a" tag.
Here's my new favorite way to solve this problem. I like this approach for its clarity and brevity.
Use this HTML:
<a onclick="deleteHike(event);" hike_id=1>Yes 1</a><br/>
<a onclick="deleteHike(event);" hike_id=2>Yes 2</a><br/>
<a onclick="deleteHike(event);" hike_id=3>Yes 3</a><br/>
With this JavaScript:
function deleteHike(event) {
var element = event.target;
var hike_id = element.getAttribute("hike_id");
// do what you will with hike_id
if (confirm("Delete hike " + hike_id + "?")) {
// do the delete
console.log("item " + hike_id + " deleted");
} else {
// don't do the delete
console.log("user canceled");
}
return;
}
This code works because event is defined in the JavaScript environment when the onclick handler is called.
For a more complete discussion (including why you might want to use "data-hike_id" instead of "hike_id" as the element attribute), see: How to store arbitrary data for some HTML tags.
These are alternate forms of the HTML which have the same effect:
<a onclick="deleteHike(event);" hike_id=4 href="javascript:void(0);">Yes 4</a><br/>
<button onclick="deleteHike(event);" hike_id=5>Yes 5</button><br/>
<span onclick="deleteHike(event);" hike_id=6>Yes 6</span><br/>
When you assign a function to an event on a DOM element like this, the browser will automatically pass the event object (in this case MouseEvent as it's an onclick event) as the first argument.
Try it like this,
a.onclick = function(e, hike_id) { }
The function associated with the selector stops working when I replace it's contents using .html(). Since I cannot post my original code I've created an example to show what I mean...
Jquery
$(document).ready(function () {
$("#pg_display span").click(function () {
var pageno = $(this).attr("id");
alert(pageno);
var data = "<span id='page1'>1</span><span id='page2'> 2</span><span id='page3'> 3</span>";
$("#pg_display").html(data);
});
});
HTML
<div id="pg_display">
<span id="page1">1</span>
<span id="page2">2</span>
<span id="page3">3</span>
</div>
Is there any way to fix this??...Thanks
Not sure I understand you completely, but if you're asking why .click() functions aren't working on spans that are added later, you'll need to use .live(),
$("#someSelector span").live("click", function(){
# do stuff to spans currently existing
# and those that will exist in the future
});
This will add functionality to any element currently on the page, and any element that is later created. It keeps you have having to re-attach handlers when new elements are created.
You have to re-bind the event after you replace the HTML, because the original DOM element will have disappeared. To allow this, you have to create a named function instead of an anonymous function:
function pgClick() {
var pageno = $(this).attr("id");
alert(pageno);
var data="<span id='page1'>1</span><span id='page2'> 2</span><span id='page3'> 3</span>";
$("#pg_display").html(data);
$("#pg_display span").click(pgClick);
}
$(document).ready(function(){
$("#pg_display span").click(pgClick);
});
That's to be expected, since the DOM elements that had your click handler attached have been replaced with new ones.
The easiest remedy is to use 1.3's new "live" events.
In your situation, you can use 'Event delegation' concept and get it to work.
Event delegation uses the fact that an event generated on a element will keep bubbling up to its parent unless there are no more parents. So instead of binding click event to span, you will find the click event on your #pg_display div.
$(document).ready(
function()
{
$("#pg_display").click(
function(ev)
{
//As we are binding click event to the DIV, we need to find out the
//'target' which was clicked.
var target = $(ev.target);
//If it's not span, don't do anything.
if(!target.is('span'))
return;
alert('page #' + ev.target.id);
var data="<span id='page1'>1</span><span id='page2'>2</span><span id='page3'>3</span>";
$("#pg_display").html(data);
}
);
}
);
Working demo: http://jsbin.com/imuye
Code: http://jsbin.com/imuye/edit
The above code has additional advantage that instead of binding 3 event handlers, it only binds one.
Use the $("#pg_display span").live('click', function....) method instead of .click. Live (available in JQuery 1.3.2) will bind to existing and FUTURE matches whereas the click (as well as .bind) function is only being bound to existing objects and not any new ones. You'll also need (maybe?) to separate the data from the function or you will always add new span tags on each click.
http://docs.jquery.com/Events/live#typefn