I'm working on some web very simple drag and drop game using html5 and javascript. After they drag the elements I have a button that verifies either the arrange is correct or not. My verify function is on an external JS file and I'm calling it using onclick inside the input tag. It works, however my boss doesnt want event handlers to be shown on the html. I'm just starting with javascript so is there a way to call an onclick event without using the onclick on a tag in the html file?
Ive read you can do it easily with jquery, but can you use it without jquery?
You can bind a click event to the button like they do in jquery:
document.onclick = function(event) {
var targetElement = event.target;
if ( targetElement.className == "myButton" ) {
// do something
alert("my button clicked");
}
};
This example works on a class name but you can change that to any attribute you want on the button or something else.
There are two meanings I got from your question.
1) You want to call onclick event of an item on particular thing.
For this you can directly call the methods you want to call onclick.
2) not showing on html that it has onclick. For this you can use something like this:
document.getElementById('id').onClick = "yourMethod()";
Hope it helps.
Related
I have a list of divs, that have individual onclick functions.
The functions lead to http links that open in new windows. I can not rewrite the onclick functions before generating the site because it is a third party rss feed that is being generated based on a rss file. Now i walt to keep the individual links but do something else with them.
The chronology would be the following:
User clicks the element that has a prewritten onclick function.
The onclick functions is blocked from opening in a new page.
The link inside the onclick function is saved for further use.
A HTML5 audio element gets the link as a source.
I have so far tried to overwrite the onclick function. Yet I lose the http link in the process.
<div class="fw-feed-item-url"
onclick="window.open('http://www.example.com/podcasts/podcast_eposode3.mp3'
, '_blank')">
$(".fw-feed-item-url").click(function(){
var audioSrcNew = eval($('.fw-feed-item-url').attr('onclick'));
audioElement.src = audioSrcNew;
console.log(audioSrcNew);
$('.fw-feed-item-url').this.attr('onclick','alert("done"); return
false;');
});
In JavaScript, callbacks and event handlers should be executed in the order they were bound, and there is no way to alter that order. The code in the onclick attribute will be bound directly after creation of the element, and will thus be the first to be executed.
The only way to prevent this is to remove the attribute, either in the source or client-side by using jQuery's .removeAttr. So override the onclick event on page load like the following sample code.
<script>
$(document).ready(function() {
var $elements = $(".fw-feed-item-url");
// Iterate over elements
$elements.each(function () {
var $elm = $(this);
// Reference to onclick attribute value for future use
var onClick = $elm.attr("onclick");
console.log(onClick);
// Remove onclick attr and bind your own click event
$elm.removeAttr("onclick").click(function () {
//Own code comes here
alert("Whoa!!!! click worked!!");
})
});
});
Referenced from
How to decide execution sequence for Javascript and Jquery function
HTML
Inside <div id='foo-bar-baz'>
I have a series of image links with unique ids as below
<a href=''><img id='12341234' class='foo-bar-thumbnail-image' src='/path/to/image.jpg'></a>
<a href=''><img id='56785678' class='foo-bar-thumbnail-image' src='/path/to/image.jpg'></a>
Javascript / JQuery
The above div is created by a $.get() to a webservice which returns a chunk of HTML in variable response. On success, the $.get() calls the below function:
var thumbnailsDiv = function (response)
{
var json = $.parseJSON(response);
$('#foo-bar-baz').html(json.html);
alert("Setting click functions on thumbnails");
$('.foo-bar-thumbnail-image').unbind().click(function () {
alert("I am thumbnail " + $(this).id);
}, false);
};
As you can see above, I'm trying to bind a click function to each of the image links. However this is not working (with or without the unbind()).
After the above code has run, if I inspect the image links in the Dev Tools, I can see that there are two click event attached already to the thumbnails. Neither of these is my function above. The paths for both of them are from other applications libraries embedded on the page: one is labelled 'jQuery' and the other is labelled 'Bubbling' and 'DOM2'. I'm guessing that it is these attached events that mean I can't add my event above, but I don't know enough about jQuery or javascript to know if this is true (I am a server-side developer normally, I don't know front-end stuff at all.)
Any suggestions as to how I get an on-click event working for these elements would be much appreciated, so that I can replace the demo code above with the code I need to run.
You should be using $(document).on('click','.foo-bar-thumbnail-image',function() ... instead of $.click(function()... since the event handler is on elements that were rendered on the page via JS. That's a "delegated" event handler - you can read more about that here https://learn.jquery.com/events/event-delegation/
You just need to bind the click event to the parent element which already exists on the page.
$('#foo-bar-baz').on('click', '.foo-bar-thumbnail-image', function(){
// what you want to happen when click
// occurs on elements that match '.foo-bar-thumbnail-image'
// within '#foo-bar-baz'
alert("I am thumbnail " + $(this).id);
});
So, i have this code snippet that opens a modal:
<button id="trigger-overlay" class="order">Open Overlay</button>
Now, i wanted to include it in Wordpress menu, but i cant add button tag there, so i added:
Open Overlay
And i am using jquery to add a ID to that link, like this:
$('.order').attr('id','trigger-overlay');
ID is added, but link doesnt open anything, aka, it links to "#" instead of opening a modal...
How could i fix this to make it work?
Thanks!
This thing may causing due to events binging order. So, your code $('.order').attr('id','trigger-overlay'); is executing right after click's binding event (I think that event looks like this one: $('#trigger-overlay').click(function() { ... });.
If you have ability to change that binding, please use jquery.on method: http://api.jquery.com/on/
So that code will looks like: $(document).on('click', '#trigger-overlay', function() { ... });.
Also you can just move $('.order').attr('id','trigger-overlay'); above the script with that event binding.
Based on your
<button id="trigger-overlay" class="order>Open Overlay</button>
I'm not sure how you got a modal to trigger, since it is not connected to an event handler like:
<button onclick="turnOverlayOn()">Demo Button</button>
In this case, there would be a function that targets the overlay/modal and turns its CSS display property from none to block or inline-block (however you would like to display it):
var turnOverlayOn = function () {
$('targetOverlayId').css('display','block')
}
I suggest focusing on attaching an onClick event that triggers a function that does what you want to make the overlay appear.
The function used to turn the overlay off could be:
var turnOverlayOff = function () {
$('targetOverlayId').css('display','none')
}
You could attach this to a different anchor tag or button to turn the overlay off.
Note: the event should work the same for an anchor tag as it does for a button.
In my understanding you want to trigger the button click event. Using the a tag with class order.
try
jQuery(document).on('click','.order',function(){
jQuery('#trigger-overlay').click();
});
You can trigger the click event using jquery. Since I have no knowledge of your DOM structure jQuery(document).on('click','.order',function().. will work even if your elements are dynamic (added to the DOM after the script execution) because the click event is bind to the document.
NOTE:
When using wordpress always use jQuery instead of $ to avoid conflicts.
I'm making a small game that involves smurf and toadstools.
I've been able to already make this. [Can't do direct image :/ Reputation = 6] http://gyazo.com/e9cab4b04e6735712cf67e69c689fb7b
Each of the white / red and white / blue circles is a button in it's own seperate div. What I wan't to do now is "attach" a clickEvent handler to each of those buttons so that whenever a button get's pressed, the image switches to either blank or the red and white ones.
The buttons are created with code as below:
var circle = document.createElement('button');
column.appendChild(circle);
and each button has it's own ID.
So is there any simple and easy way to make each button respond to a click like mentioned above?
The data I would need later is most importantly the ID of the clicked button. Since it's id has a reference to the row and column it belongs in.
An event triggered function can be attached to an element through javascript using the addEventListener() method.
The syntax of said method is the following:
element.addEventListener(event, function, useCapture);
For instance, in your case:
circle.addEventListener("click", myFunction);
The code above would obviously need the function myFunction() to be previously defined, however, the function can also be defined within the method itself:
circle.addEventListener("click", function(){
//your function
});
You can learn more about this method here.
Since you are using jQuery, I would do something like this:
var circle = document.createElement('button');
circle.className = "nameOfTheClass";
column.appendChild(circle);
Then jQuery bind click events on each object of class nameOfTheClass:
$('.nameOfTheClass').click(function(){
alert( $(this).attr('id') );
});
PS: You could also use jquery to create your dom element but since you only asked how to bind it..
You can do this a lot more easily by adding your click event to the buttons' parent rather than to each button, like so:
column.addEventListener("click",function(event){
var target=event.target,id=target.id;
if(target.nodeName.toLowerCase()=="button"){
// do stuff ...
}
},0);
This way you don't have to worry about buttons added to your column element later on in your scripts.
if you're trying plain javascript use
circle.addEventListener("click", function(){
/* your code here */
});
or if you intend to use Jquery then use
$('button').on('click', function(){
/*your code here*/
});
note this will apply on all the buttons of the page. if you want to use it for a specific button, then you can just use id or the class.
hope this helps.
I want to simulate a click on any link on a page using JavaScript. If that link has some function binded to its 'onclick' event (by any other JS I don't have any control over), then that function must be called otherwise the link should behave in the normal manner and open a new page.
I am not sure that just checking the value of the 'onclick' handler would suffice. I want to build this so that it works on any link element.
I have no control over what function maybe binded to the onclick event of the link using whichever JS library (not necessarily jQuery) or by simply using JavaScript.
EDIT: With the help of the answers below, it looks like it is possible to check for event handlers attached using jQuery or using the onclick attribute. How do I check for event handlers attached using addEventListener / any other JS library so that it is foolproof?
You can use the the click function to trigger the click event on the selected element.
Example:
$( 'selector for your link' ).click ();
You can learn about various selectors in jQuery's documentation.
EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined.
You could solve this with something like this:
var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
document.location = linkEl.attr ( 'href' );
} else {
linkEl.click ();
}
Don't know about addEventListener though.
Why not just the good ol' javascript?
$('#element')[0].click()
Just
$("#your_item").trigger("click");
using .trigger() you can simulate many type of events, just passing it as the parameter.
Easy! Just use jQuery's click function:
$("#theElement").click();
Try this
function submitRequest(buttonId) {
if (document.getElementById(buttonId) == null
|| document.getElementById(buttonId) == undefined) {
return;
}
if (document.getElementById(buttonId).dispatchEvent) {
var e = document.createEvent("MouseEvents");
e.initEvent("click", true, true);
document.getElementById(buttonId).dispatchEvent(e);
} else {
document.getElementById(buttonId).click();
}
}
and you can use it like
submitRequest("target-element-id");
At first see this question to see how you can find if a link has a jQuery handler assigned to it.
Next use:
$("a").attr("onclick")
to see if there is a javascript event assigned to it.
If any of the above is true, then call the click method. If not, get the link:
$("a").attr("href")
and follow it.
I am afraid I don't know what to do if addEventListener is used to add an event handler. If you are in charge of the full page source, use only jQuery event handlers.
All this might not help say when you use rails remote form button to simulate click to. I tried to port nice event simulation from prototype here: my snippets. Just did it and it works for me.