Two functions on Keypress won't work (textarea) - javascript

I have created two function on Enter Key press
to hide show dive on Enter key press
to auto resize textarea Height on Enter when it reached to end.
Here is the fiddle : http://jsfiddle.net/rz3f3gng/2/
$('.one').hide();
$(function() {
//hide show dive on enter press and on other keys hide div
$('#mainContent').on('keypress', function(e) {
if (e.which == 13) {
e.preventDefault();
$('.one').show();
} else {
$('.one').hide();
}
});
function TextareaAuto(o) {
o.style.height = "200px";
o.style.height = (2 + o.scrollHeight) + "px";
}
});
.one {
width: 100px;
height: 30px;
background: red;
}
textarea {
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="one">
</div>
<textarea id="mainContent" onkeydown="TextareaAuto(this)" style="overflow:hidden">
</textarea>
Only One function seems to work at time, either Hide show div or auto size textarea.

You should never mix inline event handlers with jQuery handlers. Just use two jQuery handlers or call the function from the existing handler:
e.g.
$('#mainContent').on('keypress', function(e){
if (e.which == 13) {
e.preventDefault();
$('.one').show();
}
else{
$('.one').hide();
}
TextareaAuto(this);
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/rz3f3gng/3/
Update
As you still want the Enter to work (see comment below), just get rid of your e.preventDefault()
e.g.
$('#mainContent').on('keypress', function(e){
if (e.which == 13) {
$('.one').show();
}
else{
$('.one').hide();
}
TextareaAuto(this);
});
http://jsfiddle.net/TrueBlueAussie/rz3f3gng/4/
Which now means it can be reduced using toggle() to
$('#mainContent').on('keypress', function(e){
$('.one').toggle(e.which == 13);
TextareaAuto(this);
});
http://jsfiddle.net/TrueBlueAussie/rz3f3gng/5/

Related

Hiding <div> block doesn't work on mobile

I have callback button and hidden callback form.
Form shows up after click on button and hide after click on any place on the screen except the form-space.
BUT! Form don't hide on mobile devices. I think that problem is in touch tracking on iOS.
How can i fix this problem?
function showcallbackform (objName) {
if ( $(objName).css('display') == 'none' ) {
$(objName).animate({height: 'show'}, 200);
} else {
$(objName).animate({height: 'hide'}, 200);
}
};
jQuery(function($){
$(document).mouseup(function (e){
var div = $("#callback-form");
if (!div.is(e.target)
&& div.has(e.target).length === 0) {
div.hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can bind both actions (mouse and touch events) like this:
jQuery(function($){
$(document).bind( "mouseup touchend", function(e){
var div = $("#callback-form");
if (!div.is(e.target)
&& div.has(e.target).length === 0) {
div.hide();
}
});
});

Javascript event keypress on hover

Hi I have multiple divs on the page. I want to raise an alert based on a user hovering over one of the divs and pressing control z. I need to in effect alert out what is in the span dependant upon which div the user is hovered over on.
I have tried with getbyId the problem arises with multiple elements. I am unsure if i need to bind every element.
<div class="mydiv">Keypress here!<span>test</span></div>
<div class="mydiv">Keypress here!<span>test1</span></div>
var pressed = false;
onload = function(e) {
var myElement = document.getElementsByTagName('div');
function keyaction(e, element) {
// var originator = e.target || e.srcElement;
if (e.charCode === 122 && e.ctrlKey) {
//myElement.innerHTML += String.fromCharCode(e.charCode);
alert(true);
}
}
for (var i = 0; i < myElement.length; i++) {
myElement[i].addEventListener("mouseover", function (e)
{
document.addEventListener("keypress", function(t){keyaction(t,e);}, false);
});
myElement[i].addEventListener("mouseout", function ()
{
document.removeEventListener("keypress", keyaction, false);
});
}
}
I think you are overdoing for what is needed. A simple keydown event bind on mouseover and unbind on mouseout would do the trick.
Here's an example :
<div id="wrapper">
<div class="mydiv">Keypress here!<span>test</span></div>
<div class="mydiv">Keypress here!<span>test1</span></div>
</div>
<br>
Keys Pressed :
<br>
<div id="key"></div>
$("#wrapper .mydiv").on("mouseover",function()
{
$(document).bind("keydown",function(e) {
var originator = e.keyCode || e.which;
if(e.ctrlKey)
$("#key").append(originator + ",");
});
}).on("mouseout",function()
{
$(document).unbind("keydown");
});
http://jsfiddle.net/s095evxh/2/
P.S : for some reason , Jsfiddle doesn't allow keydown event on mouseover so you might have to click manually on the div to make it work but the solution works flawless on a local system.
I would suggest that you use the normalized e.which if available. You also have code 122 which is F11 keys code not 90 related to the 'z' key.
Turn the event manager on when over and off when not per your stated desire:
$('.mydiv').on('mouseenter', function () {
$(window).on('keydown', function (e) {
var code = e.which ||e.keyCode;
$('#status').append('we:'+ code);
if (code === 90 && e.ctrlKey) {
$('#status').append('howdy');
}
});
});
$('.mydiv').on('mouseleave', function () {
$(window).off('keydown');
});
Note that I changed to post some text to a fictitious "status" div rather than your alert as that will change where the cursor hovers. Change that to some real action. There MAY be issues with the event bubbling but I will leave that determination to you.
Here is a key code list (google for more/another) https://gist.github.com/lbj96347/2567917
EDIT: simple update to push the span text into the status div:
<div class="mydiv">Keypress here!<span>test</span>
</div>
<div class="mydiv">Keypress here!<span>test1</span>
</div>
<div id="status">empty
<div>
$('.mydiv').on('mouseenter', function () {
var me = this;
$(window).on('keydown', function (e) {
var code = e.which || e.keyCode;
$('#status').append('we:' + code);
if (code === 90 && e.ctrlKey) {
$('#status').append($(me).find('span').text());
}
});
});
$('.mydiv').on('mouseleave', function () {
$(window).off('keydown');
$('#status').text('out');
});
Listen for the keypress on the window and add mouse events to the elements to toggle a variable with what element is active.
var activeElem = null;
$(".mydiv")
.on("mouseenter", function () {
activeElem = $(this);
}).on("mouseleave", function () {
if(activeElem && activeElem.is(this)) {
activeElem = null;
}
});
$(window).on("keydown", function (evt) {
if( activeElem && evt.keyCode===90 && evt.ctrlKey) {
console.log(activeElem.find("span").text());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv">Keypress here!<span>test</span></div>
<div class="mydiv">Keypress here!<span>test1</span></div>
To prevent frequent binding/unbinding of the "keydown" handler whenever the user hovers over the <div>, I would simply keep track of the <div> currently being hovered. Something like this:
var hovering = null;
$(document)
.on('keydown', function(e) {
if (e.which === 90 && e.ctrlKey && hovering) {
console.log($('span', hovering).text());
}
})
.on('mouseover', '.mydiv', function(e) {
hovering = this;
})
.on('mouseout', '.mydiv', function() {
hovering = null;
});
.mydiv:hover {
cursor: pointer;
color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv">Test <span>1</span></div>
<div class="mydiv">Test <span>2</span></div>
<div class="mydiv">Test <span>3</span></div>
<div class="mydiv">Test <span>4</span></div>
<div class="mydiv">Test <span>5</span></div>
I would propose the other way around. Listen for the keypress, and select the element which has the hover.
$(document).keypress(function(e) {
if (e.charCode === 26 && e.ctrlKey) {
console.log("Key pressed");
console.log($('.mydiv:hover span').html());
}
});
Codepen Demo
If I am understanding your question correctly, you are looking for the text value of the span within the hovered element. Traversing the DOM from $(this) will get you what you want.
$(".mydiv").mouseover(function (e) {
alert($(this).find('span').text());
});

How to execute a JS code block on pressing ESC key?

I want to execute a JS code when user presses ESC key. Please help me how can I do this? My current code is not working. I don't know where I'm doing wrong? I'm just a beginner so please help me out..
function hideModalKeyPress(e)
{
if(e.keyCode == 27)
{
document.getElementsByClassName('modalOverlay')[0].style.visibility = "hidden";
}
}
.modalOverlay
{
width: 200px;
height: 200px;
opacity: 0.8;
background-color: black;
visibility: visible;
}
<div class="modalOverlay" onkeydown="hideModalKeyPress(e);">Press ESC to hide me.</div>
/*
* I want to set the div's visibility to hidden
* when user presses ESC key
*/
You could use jQuery and do the following:
$(document).keyup(function(e) {
if (e.keyCode == 27) {
$(".modalOverlay").css('visibility', 'hidden');
}
});
JSFiddle
Or in pure JavaScript:
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
document.getElementById("modal").style.visibility = "hidden";
}
};
JSFiddle
This worked for me:
document.addEventListener("keydown", hideModalKeyPress, false);
function hideModalKeyPress(e) {
if(e.keyCode === 27)
{
document.getElementsByClassName('modalOverlay')[0].style.visibility = "hidden";
}
}
Here is the working jsfiddle:
https://jsfiddle.net/7jrfrz26/

javascript execute function pressing 'esc' key

I have 2 javascript functions: one of them shows div 'PhotoFull' another hides. 'PhotoFull' is a container Div.. Just black background for another Div inside of it. When the user clicks on black background, PhotoFull dessapears.. but if affects also the Div which is inside of 'PhotoFull' (PhotoFull dessapears while clicking the div which is inside). So For the Div which is inside I use event.stopPropagation();
Both functions work, but I also need to hide Div hideDiv() when "ESC" key is pressed. hideDiv() is executing Div
function showDiv() {
document.getElementById('PhotoFull').style.display = "inherit";
event.stopPropagation();
}
function hideDiv() {
var target = event.target || event.srcElement;
if (event.currentTarget == target) {
document.getElementById('PhotoFull').style.display = "none";
}
}
window.onload=function() {
document.onkeyup = key_event;
}
function key_event(e) {
if (e.keyCode == 27) hideDiv();
}
And HTML:
<div id="PhotoFull" style="position: absolute; width: 100%; height: 100%; background-color: rgba(0,0,0, 0.75); display:none; z-index: 999;" onclick="hideDiv()">
<div style="width: 960px; border-radius: 3px; background-color: #ffffff; margin-top: 100px;">
<img id="one_full" src="numbers/1.jpg" style="max-width: 940px; margin: 10px;" />
</div>
</div>
Without event.stopPropagation(); Pressing ESC button executes function hideDiv() but with it, nothing happens. Don't know why.
Thanks for attention
When you press Esc key it goes in hideDiv function but the condition goes worng due to below reason.
See Debug trace in picture.
See watchExpression section in debugger. I have added event object to watch.
You can see full object description in watchExpression in above image.
You have write below condition in hideDiv function
var target = event.target || event.srcElement;
if (event.currentTarget == target) {
document.getElementById('PhotoFull').style.display = "none";
}
in debug trace you can see that event.currentTarget is body target local variable in the hideDiv function is document because you have added your listener for document object canbe seen from your code
window.onload=function() {
document.onkeyup = key_event;
}
So the solution is you have to register event listener on proper object which is body.
use below code for window.onload function..
window.onload=function() {
document.body.onkeyup = key_event;
}
window.onkeypress = keypress;
function keypress(event) {
if (event.keyCode == 27) {
alert("Hidding div *magic runing...*");
}
}
You should consider using onkeypress event to handle it.
Try this,
document.onkeydown=function(e){
if(e.which == 27) {
hidediv();
return false;
}
}

on drag change stylesheets for all dropzones (file upload)

I have multiple dropzones for uploading files on a webpage
How to highlight all dropzone elements as soon as a file is dragged into the browser, so the user knows where to drop the file? And when a file is dragged over one of the dropzones I need to add an additional class to indicate the user can release the file
update
kurideja pointed me in the right direction to Dragster
https://github.com/bensmithett/dragster
Now it almost works :)
If you drag over one dropzone and drag back out without releasing the file all dropzones are hidden
http://jsfiddle.net/L7v2f96z/9/
html
<div class="dropzone"></div>
<div class="dropzone"></div>
javascript
// Add/remove class when file is dragged over the dropzone. Hover effect
$('.dropzone').dragster({
enter : function(){
$(this).show().addClass('hover');
},
leave : function(){
$(this).hide().removeClass('hover');
}
});
// Show/hide dropzones until a file is dragged into the browser window. Hide dropzones after file is dropped or dragging is stopped
var w = $(window).dragster({
enter : function(){
$('.dropzone').show();
},
leave : function(){
$('.dropzone').hide();
}
})
// Prevent defaults (file is openened in the browser) if user drops file outside a dropzone
.on('dragover', function(e){
e.preventDefault();
})
.on('drop', function(e){
e.preventDefault();
w.trigger('dragleave');
});
css
.dropzone {
width:200px;
height:200px;
background:#fff;
display:none;
border:2px dashed rgba(0,0,0,0.5);
box-shadow:0 2px 5px rgba(0,0,0,0.1), inset 0 0 40px rgba(0,0,0,0.1);
border-radius:2px;
margin:10px;
}
.dropzone.hover {
background:#e3e3e3;
}
Main problem was: after leaving the dropzone area, dragster triggered leave twice, both on .dropzone and window. Simply adding e.stopPropagation() solves the problem. There are also few more fixes (removed show() and hide() inside dropzone dragster). Your code on Fiddle and also below:
// Add/remove class when file is dragged over the dropzone. Hover effect
$('.dropzone').dragster({
enter: function() {
$(this).addClass('hover');
},
leave: function(e) {
e.stopPropagation(); //-- Critical point
$(this).removeClass('hover');
}
});
// Show/hide dropzones until a file is dragged into the browser window. Hide dropzones after file is dropped or dragging is stopped
var w = $(window).dragster({
enter: function() {
$('.dropzone').show();
},
leave: function() {
$('.dropzone').hide();
}
})
// Prevent defaults (file is openened in the browser) if user drop file outside a dropzone
.on('dragover', function(e) {
e.preventDefault();
})
.on('drop', function (e) {
e.preventDefault();
w.trigger('dragleave');
});
You can use e.originalEvent.pageXand e.originalEvent.pageY on dragover and check if its in a range of the box. For this example I have copied the dropzone and I know the width and height of the div so I could hardcode the condition. You will have to come up with a way to store the position(top and left) of the dropzone areas and use that for comparison.
var drag_timer;
$(document).on('dragover', function (e) {
var dt = e.originalEvent.dataTransfer;
if (dt.types && (dt.types.indexOf ? dt.types.indexOf('Files') != -1 : dt.types.contains('Files'))) {
if (e.originalEvent.pageX <= 200 && e.originalEvent.pageY <= 200) {
$('.dropzone').removeClass('highlight');
$('.dropzone:eq(0)').addClass('highlight');
} else if (e.originalEvent.pageX <= 400 && e.originalEvent.pageY <= 400) {
$('.dropzone').removeClass('highlight');
$('.dropzone:eq(1)').addClass('highlight');
} else {
$('.dropzone').removeClass('highlight');
}
$('.dropzone').show();
window.clearTimeout(drag_timer);
}
})
.on('dragleave', function (e) {
drag_timer = window.setTimeout(function () {
$('.dropzone').hide();
}, 50);
});
Demo Fiddle
You can use the target member of the event to get the proper element:
var drag_timer;
$(document).on('dragover', function(e){
var dt = e.originalEvent.dataTransfer;
if(dt.types && (dt.types.indexOf ? dt.types.indexOf('Files') != -1 : dt.types.contains('Files'))){
$('.dropzone').show();
window.clearTimeout(drag_timer);
}
})
.on('dragleave', function(e){
drag_timer = window.setTimeout(function(){
$('.dropzone').hide();
}, 50);
});
$('.dropzone')
.on('dragenter', function(e){
$(e.originalEvent.target).addClass('highlight');
})
.on('dragleave', function(e){
$(e.originalEvent.target).removeClass('highlight');
});
Fiddle: http://jsfiddle.net/mzcqxfq3/
Some drag events are fired on EACH element, so basically there is not a one continuous drag, but a sequence of drags over all elements below the mouse.
Just use this plugin: http://javascript.hew.io/bensmithett/dragster
In my case I wanted to change the style of the class the moment I put
a new file and when the dropzone was filled, I did the following:
.dz-drag-hover , .dz-started {
border: 2px solid #0CB598;
}
My solution would be very similar to your aproach.
When a file is draged into the window, add a css-class to the element which contains all drop-zones (body if neccessary). Then you can style your drop-zones on drag accordingly:
$(document).on('dragover', function(e){
var dt = e.originalEvent.dataTransfer;
if(dt.types && (dt.types.indexOf ? dt.types.indexOf('Files') != -1 : dt.types.contains('Files'))){
$('body').addClass('dragging'); // Adding a class to the body
}
})
.on('dragleave', function(e){
$('body').removeClass('dragging')
});
The css would be:
/* style the drop-zone */
.dropzone {
height:200px;
width:200px;
display:none;
border:2px dashed black;
}
/* show the dropzone when file is dragged into window */
body.dragging .dropzone{
display:block;
}
/* highlight box when hovered but only when file is dragged */
body.dragging .dropzone:hover{
background:gray;
}
If this isn't what you wanted pleas tell me in a comment ;)
EDIT
Of course you have to remove the class when the file is droped
$(document).on('drop', function(event) {
$('body').removeClass('dragging');
}
IE11 bug caused by dt.types.indexOf, e.originalEvent.dataTransfer.types is a DOMStringList object in ie.
So you shoud use dt.types.contains instead ofdt.types.indexOf.
The following works:
var drag_timer;
$(document).on('dragover', function(e) {
var dt = e.originalEvent.dataTransfer;
if (dt.types != null &&
(dt.types.indexOf ? dt.types.indexOf('Files') != -1 :
(dt.types.contains('Files') ||
dt.types.contains('application/x-moz-file')))) {
$('.dropzone').show();
window.clearTimeout(drag_timer);
}
})
.on('dragleave', function(e) {
drag_timer = window.setTimeout(function() {
$('.dropzone').hide();
}, 25);
});
.dropzone {
height: 100px;
width: 100px;
background: red;
display: none;
}
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<div class="dropzone"></div>

Categories

Resources