Javascript to trigger one function only if two events are both true - javascript

Say I want to activate myFunction only if the user has pressed the paragraph with a key and clicks on it. In the case below, the function will get triggered if any of the events is true.
<p id="p1" onClick="myFunction()" onKeyDown="myFunction()">
Text awaiting to be colored in red</p>
<script>
function myFunction(){
document.getElementById("p1").style.color = "red";
}
</script>

You need one extra variable isKeyDown, and isKeyDown should be set to true on keydown, and set to false on keyup.
And than in click callback check is isKeyDown true, call myFunction.

An example of how you could do it. This works with Enter and normally clicking it. Really you don't need to make p focus but I thought it was neat, even though you can still handle the key events from the document and since the click only registers on p there's nothing to worry about.
var p = document.getElementById('p1');
p.addEventListener('mousedown', function(e) {
p.clicked = true;
checkEvents(p);
});
p.addEventListener('mouseup', function(e) {
p.clicked = false;
});
p.addEventListener('keydown', function(e) {
if (e.keyCode === 13) {
p.enterDown = true;
}
});
p.addEventListener('keyup', function(e) {
checkEvents(p);
if (e.keyCode === 13) {
p.enterDown = false;
}
});
function checkEvents(el){
if(el.enterDown && el.clicked){
el.style.backgroundColor = 'red';
}
}
p:focus {
outline: none;
}
<p id="p1" tabindex='0'>
Text awaiting to be colored in red</p>

You'll need to breakdown into two methods. First is keystrokes->click and then click->keystrokes. I'm not sure if this is achievable on pure/vanilla javascaript. But on jquery it goes something like:
$('#p1' ).keydown(function() {
if($('#p1').click()) {
document.getElementById("p1").style.color = "red";
}
});
$('#p1')click(function () {
if($('#p1').keydown()) {
document.getElementById("p1").style.color = "red";
}
});

Related

How to execute function while handle 2 events at same time?

I have some code that wants to be executed while the user resizing an element and scrolling the window at the same time tow events must occur at the same time to execute the function something like the following but I want to merge them to be like one custom event?
this.on("resize", function() {
$(window).scroll(function() {
figure.setHeight(_this.getHeight());
_this.setHeight(figure.getHeight());
});
});
Explanation : I have used a flag here, initially set to false. As it is given that both events will be happening, we can make a check in one function is the other is happening or not and execute the desired function.
First of all click the button. A console will be generated, that clicked. Now flag is set to true. But myFunction() is not eecuted, coz it will fire only when keydown will take place. In case key is pressed, flag won't be true, and hence myFunction() will not be executed. Now that you know that, button was clicked, so it has the focus. On pressing enter key, it will do perform click and keydown at same time. And myFunction() will get executed. When it gets executed, set flag to false. :)
var flag = false;
$(document).on("keydown", function() {
flag = true;
console.log("key pressed");
});
$('button').click(function() {
console.log("clicked");
if (flag) {
myFunction();
}
});
function myFunction() {
alert("Both at same time");
flag = false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click me</button>
From my understanding the resize event is triggered first, and then if the user also scrolls your custom function should be called
let resizeTriggered = false
const myResizeFunc = (event) => {
resizeTriggered = true
}
const myScrollFunc = (event) => {
if (resizeTriggered) {
myCustomFunction()
}
}
const myCustomFunction = () => {
console.log('both are happening')
}
$('#textArea').mousedown(myResizeFunc)
$(window).scroll(myScrollFunc)
div.large {
height:1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="textArea"></textarea>
<div class="large">
</div>

Single click and Double click on the same element, not working; Javascript

I am trying to add a click function that triggers when a button is clicked. I am also trying to figure out how to add a double click function onto the same element, that triggers a different event.
var click = false;
onEvent("image2", "click", function(event) {
click = true;
});
if (click === true) {
setTimeout(function() {
onEvent("image2", "click", function(event) {
setScreen("safeScreen");
console.log("double click");
});
}, 200);
} else {
onEvent("image2", "dblclick", function(event) {
setScreen("safeScreen");
console.log("click");
});
}
This code is completely wrong, but I don't know where to start/correct. What am I doing wrong? I am looking to have the single click not trigger when the user double clicks.
Update:
Try passing a function clicks() to your event listener like so:
onEvent("image2", "click", clicks);
Function clicks() will check if there was a single or double click based on setTimeout function. You can adjust setTimeout via timeout variable and of course you need clickCount variable declared outside clicks() function.
Pure js approach
Try adding two event listeners. Less code, much cleaner. Check this working example.
var selector = document.getElementById('codeorg');
selector.addEventListener('click', clicks);
// Global Scope variable we need this
var clickCount = 0;
// Our Timeout, modify it if you need
var timeout = 500;
// Copy this function and it should work
function clicks() {
// We modify clickCount variable here to check how many clicks there was
clickCount++;
if (clickCount == 1) {
setTimeout(function(){
if(clickCount == 1) {
console.log('singleClick');
// Single click code, or invoke a function
} else {
console.log('double click');
// Double click code, or invoke a function
}
clickCount = 0;
}, timeout || 300);
}
}
// Not important for your needs - pure JS stuff
var button = document.getElementById('button');
button.addEventListener('click', singleClick);
button.addEventListener('dblclick', doubleClick);
function singleClick() {
//console.log('single click');
}
function doubleClick() {
console.log('double click');
}
#codeorg {
margin-bottom: 100px;
}
<h2>Double Click</h2>
<button id="button">Click me</button>
<hr><hr>
<h2>Double click or Single Click</h2>
<button id="codeorg">Click me</button>

show/hide div when user inputs text into text area?

I am trying to toggle a div so it shows and hides when a user enters text into textarea.
i am using the below code and its not working for me, can anyone please show me why? thanks
html:
<head>
<script>
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val() > 8) {
$('#cname2').toggle("slow");
}
});
});
</script>
</head>
<form>
<input type="text" id="cname" name="cname" class="field">
<div id="cname2"></div>
</form>
css:
#cname2{
width:30px;
height:30px;
position:absolute;
margin-top:-13px;
margin-left:400px;
background-image: url('tick.png');
background-repeat:no-repeat;
background-position:right;
display:none;
}
so apparently my above code doesnt work in IE 9, but i should be able to achieve what i am trying to do by using this code, but can someone please show me where i place my div ID/how i adapt it to work for me?
var activeElement = null;
var activeElementValue = null;
// On focus, start watching the element
document.addEventListener("focusin", function(e) {
var target = e.srcElement;
if (target.nodeName !== "INPUT") return;
// Store a reference to the focused element and its current value
activeElement = target;
activeElementValue = target.value;
// Listen to the propertychange event
activeElement.attachEvent("onpropertychange", handlePropertyChange);
// Override .value to track changes from JavaScript
var valueProp = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype, 'value');
Object.defineProperty(activeElement, {
get: function() { return valueProp.get.call(this); },
set: function(val) {
activeElementValue = val;
valueProp.set.call(this, val);
}
});
});
// And on blur, stop watching
document.addEventListener("focusout", function(e) {
if (!activeElement) return;
// Stop listening to propertychange and restore the original .value prop
activeElement.detachEvent("onpropertychange", handlePropertyChange);
delete activeElement.value;
activeElement = null;
activeElementValue = null;
});
function handlePropertyChange(e) {
if (e.propertyName === "value" &&
activeElementValue !== activeElement.value) {
activeElementValue = activeElement.value;
// Fire textchange event on activeElement
}
};
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val().length > 8) {
$('#cname2').show();
} else {
$('#cname2').hide();
}
});
});
One possible approach (demo):
$(document).ready(function() {
$("#cname").on('input', function() {
$('#cname2')[this.value.length > 8 ? 'hide' : 'show']('slow');
});
});
Here I assumed that in cname2 container there's some warning message, that has to be shown if length of text input is 8 or less characters. Note also that I've used oninput handler, not keyup: as it allows me to process mouse-driven cut-and-paste as well as direct input. The only drawback is that IE8 doesn't support this event (and IE9 support for it is rather buggy, as handler is not fired when character is removed from text input).
Use this Javascript function
var z = document.getElementById('cname');
z.onkeyup = function(){
document.getElementById('cname2').innerHTML = z.value;
}
Your HTML:
<input type='text' name='cname' class='field' id='cname'>
<div class='cname2' id='cname2'></div>
Checkout here: http://jsfiddle.net/iamsajeev/Q9LPv/
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val() > 8) {
$('#cname2').fadeIn("slow");
}
else
{
$('#cname2').fadeOut("slow");
}
});
});
http://jsfiddle.net/5EjP7/2/
I hope that helps
Try the following script:
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val().length > 8) {
$('#cname2').toggle("slow");
}
});
});

How can I change background colour of a button on key press?

I've been working on JavaScript on-screen keyboard kind of thing, just for experimentation. I wanted to see if I could detect which key had been pressed, and make the corresponding on-screen keyboard button change colour, similar to many online touch typing courses have.
I have tried many variations of the onkeydown command, but no luck.
//doesn't seem to do anything.
document.getElementById("a").style.backgroundColor="#004f40";
Button's id is simply it's value eg/ the A key is id="a".
Could anyone give me any ideas on how to do this?
Here is an example that sets the color first in CSS and uses javascript addEventListener to listen for a click event and changes the color of the button when clicked, it also removes the attached event listener.
CSS
#a {
background-color: yellow;
}
HTML
<button id="a">My Button</div>
Javascript
document.getElementById("a").addEventListener("click", function onClick() {
this.removeEventListener("click", onClick);
this.style.backgroundColor = "#004f40";
}, false);
On jsfiddle
This example uses the mouse click event, but you will need to look at key events instead of a mouse one, it could be one of many; e.g. keydown, keypress, or keyup.
Update: Here is one possible solution using key events.
CSS
button {
background-color: yellow;
}
Javascript
var start = 97,
end = 122,
button;
while (start <= end) {
button = document.createElement("button");
button.id = button.textContent = String.fromCharCode(start);
document.body.appendChild(button);
start += 1;
}
document.addEventListener("keypress", function onKeypress(evt) {
var element = document.getElementById(String.fromCharCode(evt.charCode || evt.char));
if (element) {
document.addEventListener("keyup", function onKeyup() {
document.removeEventListener("keyup", onKeyup);
element.style.backgroundColor = "yellow";
}, false);
element.style.backgroundColor = "#004f40";
}
}, false);
On jsfiddle
Note: this example is by no means perfect, it it just an example of how to use events.
Update: here is another example that uses all 3 events to de-bounce the keyboard when multiple keys are pressed and released. (Compare it in use with above.)
CSS
button {
background-color: yellow;
}
button:active {
background-color: #004f40;
}
Javascript
var start = 97,
end = 122,
button;
while (start <= end) {
button = document.createElement("button");
button.id = button.textContent = String.fromCharCode(start);
document.body.appendChild(button);
start += 1;
}
var keydown,
keypress = [];
document.addEventListener("keydown", function onKeydown(e1) {
keydown = e1;
}, false);
document.addEventListener("keypress", function onKeypress(e2) {
var record = {
"char": e2.char || e2.charCode,
"key": keydown.key || keydown.keyCode || keyDown.which,
"shiftKey": keydown.shiftKey,
"metaKey": keydown.metaKey,
"altKey": keydown.altKey,
"ctrlKey": keydown.ctrlKey
},
element = document.getElementById(String.fromCharCode(e2.charCode || e2.char));
if (element) {
element.style.backgroundColor = "#004f40";
keypress.push(record);
}
}, false);
document.addEventListener("keyup", function onKeyup(e3) {
var key = e3.key || e3.keyCode || e3.which;
keypress.forEach(function (record) {
if (record.key === key && record.shiftKey === e3.shiftKey && record.metaKey === e3.metaKey && record.altKey === e3.altKey && record.ctrlKey === e3.ctrlKey) {
document.getElementById(String.fromCharCode(record.char)).style.backgroundColor = "yellow";
}
});
}, false);
On jsfiddle
Note: even this is not perfect as it depends on millisecond timing to match keydown and keypress events.
Or alternatively, you could use jQuery:
$(".keyboardButton").mousedown(function(){
$(this).css("background":"#Color-when-pressed");
}
$(".keyboardButton").mouseup(function(){
$(this).css("background":"#Color-when-released");
}
Of course, replace the colors respectively.
Get jQuery
Or pure CSS:
.keyboardButton:active {
background:#Color-when-pressed;
}
.keyboardButton {
background:#Color-when-released;
}
It might be the best, since you won't have to write code for every single button you have, and you probably already have CSS classes for them.

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(){ ... }
}

Categories