Attach ClickEvent to a button via JavaScript / JQuery / Bootstrap - javascript

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.

Related

Best way to slim down my code on onclicks

I am not great at javascript/jquery for the most part but I know how to get some software to work. But my issue is that I have a whole bunch of
$("body").on("click", "button#thisid", function(event) {
//do stuff here
});
There are alot of the on clicks that use jquery post and get functions but they all have tiny and simple differences that i need to have get sent through. I dont want every single button to have an onclick event but I am not sure how to bind the event to a large list of items that need to have it attached to.
I have been trying to come up with some way to slim all these down but I want to have the best approach instead a whole bunch of crash and fails. So I am reaching out to people who know more than me in order to lead me in the correct path.
Please help
Considering your elements are dynamically injected, you will need to apply the click handler to an element that always exist on page load:
$(document).ready(function() {
$(document).on("click", "button.target", function() {
console.log($(this)[0].id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" class="target">One</button>
<button id="2" class="target">Two</button>
In the above example, the click handler is applied to document, and triggers whenever a button element with the class of target is clicked, running the code inside the function.
To combine the .get() and .post() functions, you'll have to find synonymous data. Keep in mind that you have access to $(this), so you can extract the relevant ID if need be :)
Hope this helps!
I dont exactly get what you want to do...
But the $("body") is the jquery selector which defines on which elements your listener will be bound to.
So if you want to create a listener for more different elements the probably easiest solution is creating a class like "listenedElement" which you give to every element you want the listener to react to and write write the selector like this
$('.listenedElement').on( "click", function() {});
If you just look for click listeners this one looks pretty nice as well:
https://api.jquery.com/click/
A nice way I find is having a one line for each button like so:
$('#model').on('click', openModel());
$('#openDropdown').on('click', openDropdown());
$('#shoppingCart').on('click', shoppingCart());
And then defining each of these functions:
function openModel() {
// Stuff here
}
function openDropdown() {
// Stuff here
}
function shoppingCart() {
// Stuff here
}
So instead of writing the function as a parameter, I find it neater to just do it separately and call it like above.

jQuery link instead of button trigger

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.

onclick element for an element that is not created yet

I am using the google search API and I want that when you click on an image, this image will be copied to a different location.
I created a fiddle here: http://fiddle.jshell.net/wjewg062/
It works this way: The user types in a term in the input field and images will be displayed. When he/she clicks on one twice it will displayed in the image div.
I put the onClick event listener on to the searchresults div, hence the extra click in the beginning. However, I want it to be displayed on the first click.
Now, if I comment this out
var searchresults = document.getElementById('searchresults');
searchresults.addEventListener("click", function(event){
event.preventDefault();
imageing();
});
it doesn't work. The images will be links. I believe the reason for this is that the results are displayed in gs-image-box and not created yet. I tried calling the imaging function in different other functions like the searchImg or the OnLoad but nothing work.
I thought of using a check if element is clicked function described here Detect if I'm clicking an element within an element
but I think there must be an easier way.
I'm running out of ideas, can anyone give an idea or hint?
Thanks !
The images are dynamically created right? Check out this post Event binding on dynamically created elements?
In short, events are attached to elements upon pageload. so a newly created dynamic element such as the ones that google creates, aren't attached to the event. so google probably has a way to circumvent the whole "you need to load the page to attach events to elements" thing but it requires an extra click. Using the syntax found in the post should help you.
By the way. Using Jquery doesn't really show down your site because it's usually cached in the client's browser.
The info you need is already in your searchresults eventListener. The target of this event will be the image you click, even if you add the event on a div higher in the structure.
A javascript event will by default be dispatched from the top element (window) all the way through the element that received the click, then will go back to the top. Any element that is an ancestor of the element that was clicked will receive the event info, so you can listen on any ancestor, but the target remains the element that was actually clicked.
In your case, by simply passing the target to your imageing() function, you can apply the behaviors you want without any extra manipulations.
One problem you might face, is if user clicks on searchresult but not on an img element. Then you'll have a bug, so you should handle these cases.
Something like this:
var searchresults = document.getElementById('searchresults');
searchresults.addEventListener("click", function (event) {
console.log(event.target, this);
event.preventDefault();
if(event.target.tagName == 'IMG'){
imageing(event.target);
}
});
function imageing(targetImg) {
var imageresult = document.getElementsByClassName('gs-image-box');
var xu = document.getElementById('companylogo');
var imgsrc = targetImg.src;
xu.src = imgsrc;
}
http://fiddle.jshell.net/pwjLrfnt/3/

Enable/Disable button click event on jquery smart wizard control

I'm using this control, which is the version 3 of jquery smart wizard.
This is the code of smart wizard:
$('#wizard').smartWizard({transitionEffect:'slide'});
This are helper functions in javascript:
function disableNextButton(){
var $actionBar = $('.actionBar');
$('.buttonNext', $actionBar).addClass('buttonDisabled').off("click");
}
function enableNextButton(){
var $actionBar = $('.actionBar');
$('.buttonNext', $actionBar).removeClass('buttonDisabled');
}
The css class actionBar, is used to style the area where are placed previous, next and finish buttons. The style buttonNext is applied to next button and the style buttonDisabled is used to put gray color to a button. All the referred styles are contained in smart wizard css files.
The problem is that I can disable button click event using ".off" function of jquery, but I cannot restore the original event handler with ".on".
My question is how do I restore next button click event after disabling button?
Thanks.
.off unlinks the event handler, so you need to re-attach the event handler. You can't just say
$('.buttonNext', $actionBar).removeClass('buttonDisabled').on("click");
because jQuery doesn't "remember" what the event was, or if you have more than one event, which event you wanted bound. You can use the click shorthand to specify the function like this:
$('.buttonNext', $actionBar).removeClass('buttonDisabled').click(function() {
// Code for your click goes here.
});
After reading the code of jquery smartwizard, I've decided to do the following for enableNextButton function:
function enableNextButton($wiz){
var $actionBar = $('.actionBar');
$('.buttonNext', $actionBar).removeClass('buttonDisabled')
.bind('click', function() {
$wiz.smartWizard('goForward');
return false;
});
}
The jquery wizard object is passed as a parameter.
This solves the problem of restoring click functionality, although repeating code from smart wizard.

how to call onclick on an external JS file? w/o jquery

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.

Categories

Resources