How can I figure out what button was clicked on last? - javascript

How can I figure out what button was clicked on last? For example I have:
<input type="button" name= "zoomer" value="State View" id= 'States View' onclick="zoomout()"/>
<input type="button" name= "zoomer" value="County View" id= 'Counties View' onclick="countyView()"/>
But whenever I change a RADIO button, I want it to take into account which button was clicked last (County View or State View). Is it possible to do this?

You could keep a global JavaScript variable var last_clicked which is updated in the functions zoomout() and countyView(), and then check the value of last_clicked when you change the radio button. Alternatively, you can terminate the calls to the functions within the onclick event with a semicolon, then assign the value to last_clicked inside the onclick event string (although I wouldn't recommend it as it can make your code messy).

var lastClicked = "none";
function zoomout()
{
// your code
lastClicked = "states";
}
function countyView()
{
//your code
lastClicked = "county";
}
if(lastClicked == "county")
{
}
else if(lastClicked == "states")
{
}

it's possible by using an external variable such as
var clickedLast = "";
function zoomout() {
clickedLast = "stateview";
... your code ...
}
function countyView() {
clickedLast = "countyview";
... your code ...
}

Related

Toggle text in button onclick

I'm trying to toggle the text in a button every time it's clicked, between "READ" and "NOT READ". The buttons have been created dynamically with js and placed into an HTML table. Each button has a unique ID, but the same class name.
I've written an if statement that works for the first button that is set in the table, but the same if statement wont work for the buttons created dynamically.
I've tried lots of different variations for the if statements. I'm not sure if the best way would be to access the unique id's, but I don't know how to do that.
Any help is appreciated! Thanks
Here's a repl https://repl.it/repls/SpryVisibleMining
function toggleText(){
if (readButton.innerHTML == "READ"){
readButton.innerHTML = "NOT READ";
} else if (readButton.innerHTML == "NOT READ"){
readButton.innerHTML = "READ";
} else {
null
}
}
And this is if statement that wont wont do anything
function toggleOthers() {
let toggle = document.getElementsByClassName(".readBtn")
toggle[0].addEventListener("click", () => {
if (toggle.innerHTML == "READ") {
toggle.innerHTML = "NOT READ"
} else if (toggle.innerHTML == "NOT READ") {
toggle.innerHTML = "READ"
} else {
null
}
})
}
toggleOthers()
The problem lies in how you are listening for the click events. Your toggleText function is triggered whenever you click the #readed button with the onclick attribute. But inside the toggleText function you add another event listener to the same button, adding a new event listener every time you click the button.
So every time you click the button you increment the amount of times you are calling toggleText.
Remove the onclick from the button and change the id to a class attribute. You said you would have multiple buttons, so having multiple buttons with the same id won't do it.
<button class="readed">READ</button>
Because you want to listen for the click event on dynamically created elements I suggest you use Event Delegation. This means listening for the click event on a parent element, this could be your table#shelf element, and check which element has been clicked. If A has been clicked, then do X, if B has been clicked, then do Y.
Listen for click event on your table element.
var table = document.getElementById('shelf');
table.addEventListener("click", tableClickHandler);
In tableClickHandler check which element has been clicked. You can do it by getting the clicked target and use the closest method to see if it really is the element you want to be clicked.
For example when you would have a <span> in your <button>, event.target would be <span>. But you want the <button> element. closest goes up in the DOM tree to see if it finally reaches an element that is the <button> you want and returns it.
You can do this for any button inside of your table.
function tableClickHandler(event) {
var readed = event.target.closest('.readed');
if (readed) {
toggleText(readed);
}
}
Modify your toggleText function so that it can take any <button> you throw add it that you want the text toggled in. Add a button parameter which represents the current button.
// Toggle text when clicked.
function toggleText(button) {
if (button.innerHTML == "READ") {
button.innerHTML = "NOT READ";
} else if (button.innerHTML == "NOT READ") {
button.innerHTML = "READ";
} else {
null
}
}
For example you can use this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="toggle(this)">not read</button>
<script>
function toggle(e) {
let txt = e.innerText;
e.innerText = txt == 'not read' ? 'read' : 'not read';
}
</script>
</body>
</html>
Let me know if it's not suitable for your use case ...
And also you can use querySelectorAll() to get all buttons and then set this event with a for() loop.
Try
toggleText = b=> b.innerHTML = b.innerHTML=='READ'?'NOT READ':'READ'
<button id="A" onclick="toggleText(this)">NOT READ</button>
<button id="B" onclick="toggleText(this)">NOT READ</button>
According to your repl, you also registered an onclick-Handler on your button, too.
So calling toggleText() while clicking the "Read/Not-Read"-button, will effectively register another onclick-Handler. This will repeat as often as you press the button.
This will run as follows:
run onclick-Handler toggleText(); this will register another EventListener
run the EventListener (registered first by index.js)
run the new registered EventListener (registered by button.onclick)
rinse and repeat ...
Just remove it in your HTML:
<td><button id="readed">READ</button></td>
You have to init an array named books, and each time you add a new book, you have to push the new book to the books array.
And also you have to set a flag as hasReadBook to the Book class.
When you are going to render your table row you have to write an if, for making the flag to string in dom.
function updateTable() {
//anythings needs to done for updating table.
//for hasReadBook flag you should do like this:
const hasReadBookString = books[i].hasReadBook ? "Read" : "Not Read";
}
And you need to make a loop on readBtn HTML collection, to know which index is going to change:
let books = [{...}];
let toggles = document.getElementsByClassName(".readBtn");
for (var i = 0; i < toggles.length; i++){
labels[i].addEventListener('click', function(e) {
books[i].hasReadBook = !books[i].hasReadBook;
})
}
updateTable();

Cannot modified checkbox with javascript

I have this code in html I want to change the checkbox check and uncheck event using javascript on some event so I am calling function ChangeCheckBox() on button click
<div>
<label class="checkbox line">
<input type="checkbox" id="Add" />Add</label>
</div>
<script>
function ChangeCheckBox() {
var AddCheck = 0;
if (AddCheck == 1) {
document.getElementById("Add").checked = true;
} else {
document.getElementById("Add").checked = false;
}
}
</script>
So in above condition check box should unchecked but its not happening checkbox is remaining checked after running this code
Since you are setting AddCheck = 0;, of course it will not keep it's state, because you are reseting the value. If you want to simulate a toggle, here's a simpler alternative.
<script>
function ChangeCheckBox() {
var el = document.getElementById("Add");
el.checked = !el.checked;
}
</script>
How do you link 'ChangeCheckBox()' to your button ? Can you post this code too ?
The problem is probably because the button refresh your page and so, the checkbox return to it initial state.

How to tell if a button is clicked

I have this code:
<script type="text/javascript">
function changestate()
{
var StateTextBox = document.getElementById("State");
var IgnoreTextBox = document.getElementById("Ignore");
var PlayButton = document.getElementById("Play");
if(document.getElementById("Play").onclick == true)
{
StateTextBox.value = "Happy";
}
}
</script>
<input TYPE="button" VALUE="Play with Pogo" id="Play" onClick="changestate();"/>
I'm trying to know when the button is clicked, and have that if button is clicked in the if statement. I want to know this so I can change the value that is inside the text box. The problem is, I do not know how to tell when the button is clicked. If you could help me out that would be great.
The onclick attribute identifies what should happen when the user clicks this particular element. In your case, you're asking that a function be ran; when the function runs, you can rest assured that the button was clicked - that is after all how the function itself got put into motion (unless you invoked it some other way).
Your code is a bit confusing, but suppose you had two buttons and you wanted to know which one was clicked, informing the user via the stateTextBox value:
(function () {
// Enables stricter rules for JavaScript
"use strict";
// Reference two buttons, and a textbox
var playButton = document.getElementById("play"),
stateTextBox = document.getElementById("state"),
ignoreButton = document.getElementById("ignore");
// Function that changes the value of our stateTextBox
function changeState(event) {
stateTextBox.value = event.target.id + " was clicked";
}
// Event handlers for when we click on a button
playButton.addEventListener("click", changeState, false);
ignoreButton.addEventListener("click", changeState, false);
}());
You can test this code live at http://jsfiddle.net/Y53LA/.
Note how we add event-listeners on our playButton and ignoreButton. This permits us to keep our HTML clean (no need for an onclick attribute). Both of these will fire off the changeState function anytime the user clicks on them.
Within the changeState function we have access to an event object. This gives us some details about the particular event that took place (in this case, the click event). Part of this object is the target, which is the element that was clicked. We can grab the id property from that element, and place it into the value of the stateTextBox.
Here is the adjusted HTML:
<input type="button" value="Play with Pogo" id="play" />
<input type="text" id="state" />
<input type="button" value="Ignore with Pogo" id="ignore" />​
You can know if button clicked by using a flag (true or false).
var flag = false;
window.addEventListener("load", changestate, false);
function changestate() {
var StateTextBox = document.getElementById("State");
var PlayButton = document.getElementById("Play");
PlayButton.addEventListener("click", function () {
flag = true;
})
PlayButton.addEventListener("click", change)
function change() {
if (flag) {
StateTextBox.value = "Happy";
}
}
}
Looking back on this, many years later, you could simply do:
<script type="text/javascript">
function changestate(action)
{
var StateTextBox = document.getElementById("State");
var IgnoreTextBox = document.getElementById("Ignore");
var PlayButton = document.getElementById("Play");
if(action == "Play")
{
StateTextBox.value = "Happy";
}
}
</script>
<input TYPE="button" VALUE="Play with Pogo" id="Play" onClick='changestate("Play");'/>

How to disable a Javascript Function when a different one is Enabled?

I have this function:
$(document).ready(function(){
function Fos(buttonSel, inputSel, someValue, cssProperty) {
$(buttonSel).click(function(){
var value = $(inputSel).attr("value");
$("div.editable").click(function (e) {
e.stopPropagation();
showUser(value, someValue, this.id)
var css_obj={};
css_obj[cssProperty]=value;
$(this).css(css_obj);
});
});
}
Here are three places where function is written:
Fos('#border_button', '#border-radius', 2, '-webkit-border-radius');
Fos('#background_color_button', '#background-color', 1, 'background-color');
Fos('#opacity_button', '#opacity', 3, 'opacity');
<input type="text" id="border-radius" value="20px">
<div id="border_button">BORDER RADIUS</div>
<input type="text" id="background-color" value="red">
<div id="background_color_button">Background</div>
<input type="text" id="opacity" value=".5">
<div id="opacity_button">Opacity</div>
<div id="2" class="defaultclass editable" style="<?php getStyle('2') ?>">
something
</div>
When you click the DIV with the ID= "border_button", or "background_color_button", or "opacity_button"
it waits for you to click any DIV with class="editable", ...$("div.editable").click(function (e) {... it executes the function with those parameters.
I just need a fix that will only allow ONE function with the parameters to be enabled at one time.
Currently, when you click on all three divs with ID = "border_button", or "background_color_button", or "opacity_button" AND THEN on a div with class="editable", it executes the function with ALL THREE sets of parameters.
This is bad. I can't figure it out.
You can't "disable" a function, but you can set a variable that will force it to exit right away:
var stopMe = true
function myFunction() {
if(stopMe) {
return;
}
...
}
You seem to be binding and rebinding the same functions over and over, which is probably why you have that e.stopEventPropagation in there. Try assigning the events once and then managing the current state (which button is active) and going from there:
var $currentInput = null;
$("#border_button,#background_color_button,#opacity_button").click(function() {
if ($currentInput == null) {
$currentInput = $(this).prev();
}
});
$("div.editable").click(function(e) {
if ($currentInput == null)
return;
$(this).css(GetCssProperties());
showUser($currentInput.val(), /* where does someValue come from? */, this.id)
$currentInput = null;
});
function GetCssProperties() {
if ($currentInput == null) return null;
var value = $currentInput.val();
if ($currentInput.attr("id") == "border-radius") return {
"-webkit-border-radius": value
}
if ($currentInput.attr("id") == "background-color") return {
"background-color": value
}
if ($currentInput.attr("id") == "opacity") return {
"opacity": value
}
}
working example here: http://jsfiddle.net/HUJ5A/
Run the function for tag with a specific class. And a the end of the function remove this class from the tag.
jQuery(".myclass").click(function(){
/* do something */
jQuery(this).removeClass('myclass');
});
Can't tell everything from your question. But this part $("div.editable").click(function (e) { will bind multiple click events to div.editable each time the user clicks Foo arugments[0] or buttonSel.
This could be a pssible solution:
Have a global variable (or HTML hidden input) say, lastDivClicked, to store the id of the recently clicked div
Update lastDivClicked everytime one of those three divs are clicked upon
Change your function to this:
function Fos(inputSel, someValue, cssProperty) {
var buttonSel = $('#lastDivClicked').val();
$(buttonSel).click(function(){ ... }
}

To disable image

I have an html image. In its onClick event I have written code to show a calendar. I want to disable that image, which means I should not be able to click that image, but the image should be visible. I want to disable the onclick event of image. Can anybody help?
Or without making any changes to your calendar...
<div>Click the button because I am enabled... <img id="btnSubmit" src="submitbutton.gif" onclick="Foobar(this,event);" alt="submit button" /></div>
<p>
<span onclick="ToggleOnclick('btnSubmit');">Click here to disable/enable the image's onclick</span>
</p>
<script>
function ToggleOnclick(elID)
{
/// <summary>
///
/// </summary>
var el = document.getElementById(elID);
if (el.onclick)
{
// Disable the onclick
el._onclick = el.onclick;
el.onclick = null;
alert(el.id +'\'s .onclick has been disabled.');
}
else //if (!(button._onclick))
{
// Disable the onclick
el.onclick = el._onclick;
el._onclick = null;
alert(el.id +'\'s .onclick has been enabled.');
}
}
function Foobar(el, e)
{
alert('Submitting...');
}
</script>
The gold is in the ToggleOnclick. In fact you could generalise that any use it to disable/enable events on just about anything.
I assume you have something like:
...
<script>
var Calendar = function() {
var month = ...;
var updateDisplay = function() {
...
};
return {
prevMonth: function() {
month--;
updateDisplay();
}
};
};
var cal = new Calendar();
</script>
Calendar is a class with private members, cal is an instance of that class.
All you should have to do is add a new member to Calendar that tracks if your onclick should be disabled, e.g. isDisabled, and check for this in the function you call in your onclick, e.g.
prevMonth: function() {
if (isDisabled) {
return;
}
month--;
updateDisplay();
}
easiest method is to use some hidden field or javascript variable
HiddenField:
<asp:HiddenField id="hdnValue" runat="server" value="true"/>
<script type="text/javascript">
function ImageClickHandler(){
var i=document.getElementById(<%=hdnValue.ClientID%>).Value;
//don't know if .value works because I'm very much into jQuery
if(i=='true') //go ahead and show calendar
else //don't show !
}
</script>
Variable:
var showCal = "<%= VARIABLE_TO_SET_IF_CAL_ENABLED%>";
<script type="text/javascript">
function ImageClickHandler(){
if(showCal=='true') //go ahead and show calendar
else //don't show !
}
</script>
As has been said, just add a condition within the onclick handler.
<script type="text/javascript">
var _imageClickDisabled = false;
function disableImageClick()
{
_imageClickDisabled = true;
}
function onImageClick()
{
if (_imageClickDisabled)
{
return;
}
// show your calendar here
//
// : : :
}
</script>
<img ... onclick="onImageClick()" />
Just call the disableImageClick() function to stop the calendar showing.
Hi it is very very late,
But I too have got same requirement and I have fixed it by replacing the image tag with input element with type as image, the benefit of this element is it show the image as input element and disabled property will allow you disable click event. Below is the code I have used
<input type="image" src="<date icon>"
onclick="return showCalender('txtdate','dd\mm\y');" disabled="disabled"></input>
Keep in mind that, the disabled attribute will only work for form related elements
Thought might be helpful for other guys in future.

Categories