div into a js button [duplicate] - javascript

This question already has answers here:
Add click event on div tag using JavaScript
(6 answers)
Closed 5 years ago.
I have a <div> that I have formatted very carefully to look nice, and I need to make it have the functionality of a button. How would I go about doing this?

You can give that div tag a onclick function as follows.
function myfns() {
console.log("Clicked")
}
<div id="btn" onclick="myfns()">Click</div>

First recommendation is to use a <button> instead. You can style that however you want as well. If that is not an option for some reason, you'll have to do a few different things to create a proper button out of a div element (to ensure that it works with keyboard and screen readers).
Add click handler. Eg btn.addEventListener('click', clickHandler);
Add enter key handler. Eg btn.addEventListener('keyup', keyHandler);
Add button role. role="button"
Add it to tab order: tabindex="0"
var buttons = document.querySelectorAll('.btn');
buttons.forEach(function (btn) {
btn.addEventListener('click', function(e) {
console.log('clicked');
});
btn.addEventListener('keyup', function(e) {
if (e.key === 'Enter') {
console.log('keyup');
}
});
});
.btn {
display: inline-block;
background: #eee;
border: 1px solid #aaa;
padding: 6px;
cursor: pointer;
}
<div class="btn" role="button" tabindex="0">My Button</div>
<div class="btn" role="button" tabindex="0">My Button</div>
<div class="btn" role="button" tabindex="0">My Button</div>

document.getElementByID("#divID").addEventListenet('click',()=>{
//write your logic
})
handle all button event similarly
e.g. doubleclick etc

Like if you have div
<div class="demo" >
....
</div>
And If you are using javascript
document.getElementsByClassName('demo')[0]
.addEventListener('click', function (event) {
// do something
});
using jquery u can do like
$(".demo").click(function(){
//do something
});

Related

How to add onClick attribute to a button with JS?

How can I add onClick attribute to this button using JS?
<button type="submit" name="add-to-cart" value="41" class="single_add_to_cart_button button alt">BUY NOW</button>
You can do it using Jquery:
"your element".addEventListener('click', function(){
alert('hey');
}, false);
you can use the JS function .addEventListener(), Here you'll find a well done explenation of It.
What I sugger you to do is to add an Id to your button tag and then use the document.getElementById() (if you don't know what this JS function does read this) to find your button and apply to It the .addEventListner() function to add a click behaviour.
I made a simple code example below, take a look at It and let me know if this answer is what you're searching for.
document.getElementById('myButton').addEventListener('click', () => {
document.getElementById('myButton').classList.toggle('toggled');
});
button {
width: 100px;
height: 50px;
background: #ccc;
border: 0;
outline: 0;
}
button:hover {
cursor: pointer
}
button.toggled {
background: red;
}
<html>
<head></head>
<body>
<button type=submit id="myButton">
CLICK ME
</button>
</body>
</html>
If you want to do it in js, you will have to either use .addEventListener() function or .onClick() function that are triggered whenever the button is clicked
you can also use the .onClick inside of your html
<button type="submit" name="add-to-cart" value="41" class="single_add_to_cart_button button alt" onClick="function_name">BUY NOW</button>
sidenote: if you want to access the button element inside your javascript you can add an Id to your button tag and then use the document.getElementById() or use let var = document.getElementByClass() but be aware to use var[0] to access the button element in case you filtered it by class

How to get event target/this without putting the event listener in the HTML tag? [duplicate]

This question already has answers here:
Get clicked element using jQuery on event?
(6 answers)
Closed 5 years ago.
I'm not a big fan of putting my event listeners (specifically onclick in this case) in the HTML, mostly because I can't use
$(document).ready(function(){})
I would much rather define the buttons' onclick as I've commented it in the startup function. However, this doesn't refer to the clicked button when I put the listener in the script (I'm guessing because it doesn't "know" which button I clicked). I've tried setting event as a parameter to the showImage function, and finding the e.target inside it, but this didn't work either. Is there a way I can refer to the clicked button without having the onclick inside the HTML tag?
//$(document).ready(function() {
window.onload = startup;
function startup() {
$("img").hide();
//$("button").click(showImage(this));
}
function showImage(e) {
var chosen = e.value;
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
//});
body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="pig" src="http://www.igjerstad.no/sites/default/files/styles/nodeimage/public/field/image/gris-750-5.jpg?itok=TJa-iUVg">
<img id="cow" src="https://www.matmerk.no/cms/images/3675/1200/1200/ku-nyt-norge.jpeg">
<img id="sheep" src="https://media.timeout.com/images/103778879/630/472/image.jpg">
<img id="hen" src="http://africahitz.com/wp-content/uploads/2017/01/hen-white-and-black-color.jpg">
<br>
<button value="pig" onclick="showImage(this)">Gris</button>
<button value="cow" onclick="showImage(this)">Ku</button>
<button value="sheep" onclick="showImage(this)">Sau</button>
<button value="hen" onclick="showImage(this)">Høne</button>
Thanks in advance!
PS. I would guess someone else has had this problem and maybe asked about it here. I did check if I could find a similar question on the site, but found nothing. However, I have failed to find that before, so I'm sorry if this is a duplicate.
PS2. The images in my code are not mine, nor do I have the rights for them. Please don't sue me ':D
PS3(!!). I'm not an experienced programmer, my terminology might be wrong some places. Feel free to correct me :)
Firstly you need to define function() in a click function so it should look like this:
$("button").click(function() {
//code to execute here
});
Instead of this:
$("button").click(//code to execute here);
When calling this in a button it will refer to the button and if I understand your code right, the image is hidden therefore if that is the button then you can't click a hidden image, if you're using a separate button to hide the image then in the click function you need to have e stated as the image element.
To use this you also need to call it as $(this) not just this.
This should work.
//$(document).ready(function() {
window.onload = startup();
function startup() {
console.log("window loaded");
$("img").hide();
$("button").click(function() {showImage(this)});
}
function showImage(e) {
console.log("onside eras");
var chosen = e.value;
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
//});
this will be set inside the event handler as event.currentTarget Ref. If you are using jQuery you can make a jQuery object from it by doing $(this). So to get the value you can do:
var chosen = $(this).prop('value');
I have also added a class myclass to the buttons to select it using $('.myclass') so that this can be seperated from other possible buttons in the page. You can also do $('button') instead to select all buttons irrespective of the class.
UPDATE
Just saw your commented out code:
$("button").click(showImage(this)); // When a button is clicked
// call the function returned by showImage(this).. err it doesnt return
// a function so it fails.
you should pass a function reference or simply a function name to the click event registration. like .click(showImage) without any function call (). In your code it will execute showImage(this) and bind the returned value to the event listener, which will apparently fail.
It should actually be:
$("button").click(showImage); // when a button is clicked
// call the function showImage with this=<clicked button> and param=event
and this will be automatically set inside the function as event.currentTarget
$(document).ready(function() {
window.onload = startup;
function startup() {
$("img").hide();
//$("button").click(showImage(this));
}
function showImage(e) {
var chosen = $(this).prop('value');
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
$('.myclass').on('click', showImage);
});
body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="pig" src="http://www.igjerstad.no/sites/default/files/styles/nodeimage/public/field/image/gris-750-5.jpg?itok=TJa-iUVg">
<img id="cow" src="https://www.matmerk.no/cms/images/3675/1200/1200/ku-nyt-norge.jpeg">
<img id="sheep" src="https://media.timeout.com/images/103778879/630/472/image.jpg">
<img id="hen" src="http://africahitz.com/wp-content/uploads/2017/01/hen-white-and-black-color.jpg">
<br>
<button value="pig" class="myclass">Gris</button>
<button value="cow" class="myclass">Ku</button>
<button value="sheep" class="myclass">Sau</button>
<button value="hen" class="myclass">Høne</button>

click event on button prevented for some reason

I'm trying to modify the css properties of a div by triggering a click event. For some reason, this isn't happening and it's driving me crazy. Do you know why this happens?
The event looks like this:
$("#colButton3").on("click", function() {
unCollapse('#CarouselSpace','#CarouselBody');
});
The unCollapse function is this:
var unCollapse = function(headerElement, bodyElement) {
$(headerElement).css('margin-top', '1500px');
$(bodyElement).css('min-height', '820px');
};
And the button itself is generated with jquery, but its html is:
<button class="btn btn-success" href="#" id="colButton3" style="display: inline-block;">Learn More</button>
The target divs are these:
<div id="CarouselSpace" class="row"><h1 id="CarouselHeader"></h1></div>
<div id="CarouselBody" class="row"></div>
What am I doing wrong?
Thank you guys.
Dynamic elements needs to have the bind on the document not the element itself as the element is loaded after the document loads
$(document).ready(function() {
$(document).on("click", "#colButton3", function() {
unCollapse('#CarouselSpace', '#CarouselBody');
});
});
var unCollapse = function(headerElement, bodyElement) {
$(headerElement).css('margin-top', '1500px');
$(bodyElement).css('min-height', '820px');
};
#CarouselBody,
#CarouselSpace {
border: 1px solid #ff6600;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="CarouselSpace" class="row">
<h1 id="CarouselHeader">Header</h1>
</div>
<div id="CarouselBody" class="row">Body</div>
<button id=colButton3>button
</button>
The code should work, you are probably trying to bind click event before you create the button. Try using $.live or bind after creating the button.

How to onclick outside an input element which is inside a div?

It maybe easy but i can't think anything to find the way when i click outside the textbox to alert something in javascript BUT when i click inside the text nothing to happen.The input text is inside the div element.
So,let's assume that my html is like bellow:
<div id="myone" onclick="javascript: myfunc();">
<input type="text" id="myInput"></input>
</div>
function myfunc()
{
alert('ok');
}
How to change that?
Thank you a lot!
Do this:
var div = document.getElementById('myone');
var funct = function(){
var input = div.querySelector("#myInput");
return false;
};
div.onclick = funct;
You shoud use this condition. e.target !== this
It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.
Use it inside your click function like this and see it in action:
$('.divover').on('click', function(e) {
if (e.target !== this) return;
thefunc();
});
var thefunc = function myfunc() {
alert('ok');
}
.divover {
padding: 20px;
background: yellow;
}
span {
background: blue;
color: white;
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='divover'>somelabel:
<span><input type="text" class="as" name="forename"></span>
</div>
This will work, if you do this carefully.
<div id="myone" onclick="javascript: myfunc();">
//your stuff in the clickable division.
</div>
<div style="position:absolute;">
<!--Adjust this division in such a way that, it comes inside your clickable division--><input
type="text" id="myInput"></input>
</div>
//Your script function/code here
function myfunc()
{
alert('ok');
}

How to catch any click event in jquery [duplicate]

This question already has answers here:
jQuery click() event catch-all?
(2 answers)
Closed 9 years ago.
I have a button, when it's clicked, shows a div with images(like an emoticon panel of a chat) if I click it again the div hides, but what I want to do is:
If the div is already showed up and then I click any other thing of the page, I want to hide it. I tried this:
$("myBtn").click(function(){
// show div
});
$(document).click(function(){
// hide div
});
When "myBtn" is clicked, the div shows up and hide automatically. How could I fix it ?
Thank you for your time.
You could try the following:
$(document).on('click', function(evt) {
if(!$(evt.target).is('#my-id')) {
//Hide
}
});
UPDATE
Just so you can have a full working set:
$('#mybutton').on('click', function(evt) {
$('#mydiv').show();
return false;//Returning false prevents the event from continuing up the chain
});
At the same time you show your original <div>, add a new <div> to your page that has a style/css set like this:
.ui-widget-overlay {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
z-index: 100;
}
Make sure the original <div> -- the one you want to be able to click on without closing it -- has a higher z-index, but everything else on the page has a lower z-index.
When you add the new div to your page, give it the .ui-widget-overlay class, and add a click handler to intercept clicks on that <div>. Adding the overlay div with the click handler looks like this:
$('<div class="ui-widget-overlay">')
.click(function() {
$('.ui-widget-overlay').remove();
$('selector-for-original-div').hide();
})
.appendTo('body');
The upshot of all this: You have two divs. The first is what you want to display and allow users to click in without closing it, the second is an invisible div underneath the first taking up the entire browser window so that if the user clicks anywhere but the upper div, it intercepts the click event. Inside that click event, you remove the hidden div and hide the original.
updated
Assuming that you have a class 'active' to the element when it shows, it would be:
$('html').click(function(e){
if(!$(e.target).attr("id") == "my-id") {
}
});
<script type="text/javascript">
$('body').click(function() {
if($("div").is(':visible')){
$("div").hide();
}
});
</script>
the $("div") selector here should be your div that is either has id or class for example: if the <div class="class" id="id"> then $("div") will be changed to $("div.class") or $("div#id")
<div class="slControlWrapper">
<div class="slControlLabel">
<asp:Label ID="lblSL" CssClass="lblSL" runat="server">Clickable Label</asp:Label>
</div>
<div class="slControlSeparator">
</div>
<div class="slControlDropDown">
</div>
<div id="wndSL">
This is the hidden content of my DIV Window
</div>
<div id="test">
I am for test click on me
</div>
</div>
$('.slControlLabel, .slControlDropDown').bind('click',function(event){
$('#wndSL').show();
event.stopPropagation();
});
$('html').click(function() {
$('#wndSL').hide();
});
#wndSL {
display:none; background-color: blue; height:500px; width:590px;
}
Have a gander here:
http://jsfiddle.net/nCZmz/26/

Categories