How to de-select a button using JavaScript - javascript

I have a button that a user is supposed to click to upload files:
window.URL = window.URL || window.webkitURL;
var button = document.getElementById("button"),
fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
button.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault();
}, false);
function handleFiles(files) {
if (!files.length) {
fileList.innerHTML = "<p>No files selected!</p>";
} else {
fileList.innerHTML = "";
for (var i = 0; i < files.length; i++) {
var videoFile = document.createElement("video");
videoFile.setAttribute("id", "recording");
videoFile.src = window.URL.createObjectURL(files[i]);
videoFile.height = 240;
videoFile.width = 320;
videoFile.setAttribute("controls", true);
videoFile.onload = function() {
window.URL.revokeObjectURL(this.src);
}
fileList.appendChild(videoFile);
}
}
}
Then the user is supposed to use the space bar to pause/play a video. My problem is after the user clicks the button, the button stays clicked so when he or she pushes the space bar, the button is liked again. To solve this problem, the user would have to click somewhere else on the screen (except for the button) and then the space bar will work to pause/play the video. But I do not want the user to click somewhere else. So I tried to click a span element using JS but it did not work:
document.getElementById("spanElement").click();
This click is supposed to simulate the click the user would on the screen, but it doesn't work because when the spacebar is pressed, the button is clicked.
Any suggestions to solve this?
Thank you

Using HTMLElement.blur() should have the desired effect.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur
button.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault();
e.target.blur();
}, false);
This will remove focus from the element once clicked.

That happen because after the click on the button it still focused, so to solve that behavior you could use .blur() in the end of click event.
The blur() method is used to removes keyboard focus from the current element.
button.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.target.blur(); //Remove focus after click
e.preventDefault();
}, false);
Hope this helps.

You could also add css to the button - pointer events
to disable button: $("#buttonId").css("pointer-events", "none");
to reactivate button: $("#buttonId").css("pointer-events", "auto");

Related

how to close created div by clicking outside of it?

I have a div that is created on a button pressed and I'm trying to have it deleted by clicking outside of it but it takes the original button press as clicking outside and immediately closes the div.
closediv();
}
function closediv() {
document.addEventListener("click", (evt) => {
const maindiv = document.getElementById('div3');
let targetElement = evt.target;
do {
if (targetElement == maindiv.childNodes[1]) {
return;
}
targetElement = targetElement.parentNode;
} while (targetElement);
var viewpost = maindiv.childNodes[1];
viewpost.parentNode.removeChild(viewpost);
});
}
In your button click handler, you could use
theButton.addEventListener("click", function(ev) {
ev.stopPropagation();
// rest of the code
});
and the click event would not propagate to the parent containers.
just add a click event on body to close your div and then add prevent default into your div to block closing action when user click on your div
document.body.addEventListener('click', (e) =>{
//close your div here
})
document.addEventListener("click", (evt) => {
evt.preventDefault()
// your code
}

How to manipulate like button on Facebook web page?

I'm currently building a chrome extension and I'm trying to get it to be able to stop a like on Facebook from going through even after the like button has been clicked. In my content.js, I currently have the code:
document.querySelectorAll('a[data-testid="fb-ufi-likelink"]').forEach(function(element) {
element.addEventListener('click', function() {
var r = confirm("You clicked like");
if (r == true) {
alert("you clicked OK");
} else {
alert("you clicked Cancel")
}
})
});
As of now, when the like button is clicked, a confirm box pops up but the like does not go through until "OK" or "Cancel" is clicked.
How do I prevent the like action from going through when the 'cancel' button is clicked? Thanks!
Try the following.
document.querySelectorAll('a[data-testid="fb-ufi-likelink"]').forEach(function(element)
{
element.addEventListener('click', function(e) {
var r = confirm("You clicked like");
if (r == true) {
alert("you clicked OK");
} else {
alert("you clicked Cancel");
e.preventDefault();
}
});
});
For reference : https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
You could try replacing the original function with a different function of your own.
document.querySelectorAll('a[data-testid="fb-ufi-likelink"]')[0].onclick =
e => console.log('blablabla!')
document.querySelectorAll('a[data-testid="fb-ufi-likelink"]').forEach(function(element) {
let originalOnClick = element.onclick
element.onclick = null
element.addEventListener('click', function(e) {
console.log('look ma, no hands!')
originalOnClick(e)
})
})
Like
I tested it on Facebook and it works there too.
Obviously you have to adapt this concept to your needs.
You can use event.preventDefault()
Just add the parameter to your listener function
function(event){
...
event.preventDefault();
}

JQuery focus and click running on same time on element

I have a button which has 2 different behaviors
While navigating with keyboard with tab key, when the button gets blur is should move focus to button 1
When we hit enter key, then it should move focus to button 2
Case 1 is working fine, but when we hit enter key the focus moves to Button 2 and then moving to button 1, Here I found blur also calling when we hit the enter button so it calling the concern function, is there any way to achieve my goal?
$('#btn').on('focus', function(){
}).on('blur', function(){
setTimeout(function() {
$('.span-hlo')[0].focus();
},250);
});
$('#btn').on('click', function(){
setTimeout(function() {
$('.span-welcome')[0].focus();
},250);
});
Fiddle example
Update your jquery Like this
var lastClick = null;
$('#btn').mousedown(function(e) {
lastClick = e.target;
}).focus(function(e){
if (e.target == lastClick) {
$('.span-welcome')[0].focus();
} else {
$('.span-hlo')[0].focus();
}
lastClick = null;
});

How to manage events on a specific div?

I would like to catch some events for a specific div if the user clicked on the div (focus the div), keyboard events are catch (not if the last click was out of the div (unfocus the div)
I tried some things, but haven't succeeded : JSFiddle
document.getElementById("box").onkeydown = function(event) {
if (event.keyCode == 13) { // ENTER
alert("Key ENTER pressed");
}
}
This code doesn't work even if I click on the div.
Pure JS solution please
The div element isn't interactive content by default. This means that there isn't a case where the return key will ever trigger on it. If you want your div element to be interactive you can give it the contenteditable attribute:
<div id="box" contenteditable></div>
In order to now fire the event you need to first focus the div element (by clicking or tabbing into it). Now any key you press will be handled by your onkeydown event.
JSFiddle demo.
Giving the 'div' a tabindex should do the trick, so the div can have the focus:
<div id="box" tabindex="-1"></div>
If you click on the div it gets the focus and you can catch the event.
JSFIDDEL
If you set 'tabindex' > 0 you can also select the div using TAB.
You could catch all the click events, then check if the event target was inside the div:
var focus_on_div = false;
document.onclick = function(event) {
if(event.target.getAttribute('id') == 'mydiv') {
focus_on_div = true;
} else {
focus_on_div = false;
}
}
document.onkeyup = function(event) {
if (focus_on_div) {
// do stuff
}
}
try this code i hope this work
var mousePosition = {x:0, y:0};
document.addEventListener('mousemove', function(mouseMoveEvent){
mousePosition.x = mouseMoveEvent.pageX;
mousePosition.y = mouseMoveEvent.pageY;
}, false);
window.onkeydown = function(event) {
var x = mousePosition.x;
var y = mousePosition.y;
var elementMouseIsOver = document.elementFromPoint(x, y);
if(elementMouseIsOver.id == "box" && event.keyCode == "13") {
alert("You Hate Enter Dont You?");
}
}
DEMO

The simplest solution to hide calendar on blur or click

http://jsfiddle.net/SXrAb/
Following the jsfiddle link there is a simplified sample of what I need. Currently it shows the calendar on button click, and hides it on input blur.
What I cannot implement additionally is hiding calendar on button click.
So - calendar should:
open on button click if hidden (done)
hide on blur (done)
hide on button click if opened (this is what I'm in stuck with, because blur is triggered before button click event so I have no chance to handle it properly)
UPD:
the solution is expected to work correctly in all cases, like "mousedown on button, drag below, mouseup" (otherwise I wouldn't ask it ;-)
Try this:
var $calendar = $('#calendar');
var mousedown = false;
$('#calendar-input').blur(function() {
if (!mousedown)
$calendar.hide();
});
$('#calendar-button').mousedown(function() {
mousedown = true;
});
$('#calendar-button').mouseup(function() {
mousedown = false;
});
$('#calendar-button').click(function() {
if ($calendar.is(':visible')) {
$calendar.hide();
}
else {
$calendar.show();
$('#calendar-input').focus();
}
});
Demo here: http://jsfiddle.net/Tz73k/
UPDATE: OK, I moved the mouseup event to the document level. I don't think the mouse state can be tricked now by dragging the mouse before releasing it:
var $calendar = $('#calendar');
var mousedown = false;
$('#calendar-input').blur(function() {
if (!mousedown)
$calendar.hide();
});
$('#calendar-button').mousedown(function() {
mousedown = true;
});
$(document).mouseup(function() {
mousedown = false;
});
$('#calendar-button').click(function() {
if ($calendar.is(':visible')) {
$calendar.hide();
}
else {
$calendar.show();
$('#calendar-input').focus();
}
});
Updated fiddle: http://jsfiddle.net/yQ5CT/
It's helpful to think of the calendar and the button as a set, where you only hide the calendar when everything in the set has blurred. To do this you need a system where focus can be "handed off" between the calendar and button without triggering your hide function. To do this you'll need a focus and blur handler on both your calendar and your button, as well as a state variable for isFocused.
var isFocused;
jQuery('#calendar,#calendar-button,#calendar-input').blur(function(){
isFocused = false;
setTimeout(function() {
if (!isFocused) { hide(); }
}, 0);
});
jQuery('#calendar,#calendar-button,#calendar-input').focus(function(){
isFocused = true;
});
The setTimeout is because, when you click the button, focus is lost on calendar before it's gained on the button, so there's momentarily nothing in focus.
Edit
I guess there's actually three elements in the set, the button, the textbox, and the calendar. I updated the example. This also fixes the issue that, in your example, you can't click between the calendar and the textbox without the calendar hiding. Presumably the real calendar can be manipulated by clicking it.
Edit 2
For this to work you'll need to make your calendar focusable by giving it a tabindex.
<span id="calendar" tabindex="-1">I'm a calendar ;-)</span>
Hiya Demo here http://jsfiddle.net/SXrAb/50/ -- (non alert version) http://jsfiddle.net/SXrAb/51/
Thanks zerkms!
JQuery Code
var $calendar = $('#calendar');
$calendar.hide();
var isBlurEventInvoked = true;
var calendarShow = false;
$('#calendar-input').blur(function() {
alert(isBlurEventInvoked + " ==== " + calendarShow);
if (isBlurEventInvoked && calendarShow){
$calendar.hide();
isBlurEventInvoked = true;
}
});
$('#calendar-button').click(function() {
if (!$calendar.is(':visible') && isBlurEventInvoked){
$calendar.show();
$('#calendar-input').focus();
calendarShow = true;
isBlurEventInvoked = true;
}else if ($calendar.is(':visible')) {
$calendar.hide();
isBlurEventInvoked = false;
calendarShow = false;
}
});
​

Categories

Resources