Javascript Toggle on keydown - javascript

I'm pretty new when it comes to getting my head around JS functions. Everything I've used before, I've tended to use as-is, but I've been trying to combine and modify a function to get a Div to toggle (height & opacity) on a specific keypress. I have the first part (can get the div to show on a 'ctrl + o' combo), but can't combine it with an if statement to show or hide, based on current display status.
Current working 'show only' JS:
$(document).keydown(function (e) {
if (e.keyCode == 79 && e.ctrlKey) {
document.getElementById('thediv').style.height = 'auto';
document.getElementById('thediv').style.opacity = '1';
return false;
}
});
Not working 'toggle on/off' JS (I've tried changing this all over the place; this is more to give an idea of what I'm trying to achieve):
$(document).keydown(function (e) {
if (e.keyCode == 76 && e.ctrlKey) {
function toggler('thediv') {
var myDiv = document.getElementById('thediv').style.height;
if (myDiv == "auto") {
document.getElementById('thediv').style.height = "0px";
document.getElementById('thediv').style.opacity = "0";
} else {
document.getElementById('thediv').style.height = "auto";
document.getElementById('thediv').style.height = "1";
}
}
}
});
Any help would be really appreciated!

You want to show and hide an element, why set its height and visibility? Just show/hide it with toggle.
$(document).keydown(function (e) {
if (e.keyCode == 76 && e.ctrlKey) {
$("#thediv").toggle();
}
});
Looking at your code
$(document).keydown(function (e) {
if (e.keyCode == 76 && e.ctrlKey) {
//This funciton is never called, you define it, do not call it!
function toggler('thediv') { //<-- Error Here, you have a string as an argument?
var myDiv = document.getElementById('thediv').style.height;
if (myDiv == "auto") {
document.getElementById('thediv').style.height = "0px"; //<--Bad practice using document.getElementById('thediv') over and over. Store it into a variable and reference it.
document.getElementById('thediv').style.opacity = "0";
} else {
document.getElementById('thediv').style.height = "auto";
document.getElementById('thediv').style.height = "1";
}
}
}
});

Related

Onkeypress slideshow with description change

I'm here for help. I'm creating some onkeypress wannabe slideshow using javascript. Code I used is down there. I'd like to add some description to the photos I used and I want it to change to correspond with the current picture, so when I have "picture 1", text "description 1" is shown, then "picture 2" and "description 2" appears etc... Any suggestions, please?
Thanks for help!
PS.: If youre willing to help me, please keep in mind, that I have no idea what I'm doing...
let images = ["https://static.boredpanda.com/blog/wp-content/uploads/2017/03/189578_205761_4_-Yuan-Peng-China-Shortlist-Professional-Sport-2017-Sony-World-Photography-Awards-58c68fa8b4532__880.jpg",
"https://static.boredpanda.com/blog/wp-content/uploads/2017/03/212367_227257_1_-Adi-Bulboac-Romania-Shortlist-Professional-Architecture-2017-Sony-World-Photography-Awards-58c68fe283e62__880.jpg",
"https://static.boredpanda.com/blog/wp-content/uploads/2017/03/217609_232497_0_-Wilson-Lee-China-Shortlist-Open-Competition-Still-Life-2017-Sony-World-Photography-Awards-58c68fed34611__880.jpg"];
function changeImage(dir) {
let img = document.getElementById("imgClickAndChange");
img.src = images[images.indexOf(img.src) + (dir || 1)] || images[dir ? images.length - 1 : 0];
}
document.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == '37') {
changeImage(-1) //left <- show Prev image
} else if (e.keyCode == '39') {
// right -> show next image
changeImage()
}
}
You can download this jQuery-sliderResponsive and call the function on your key up and key down. The code work for only this slider.
document.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == '37') {
prevSlide(); // Previous
} else if (e.keyCode == '39') {
nextSlide(); // Next
}
}
You should use an existing plugin.
However, if you would like to go on this path you could have another array with the descriptions, matching the positions.
Something like this should work:
let descriptions = ["It hurts!", "This is a room with small chairs (no kidding!!)", "Painting?"];
let currentIndex = 0;
function changeImage(dir) {
// Get the index
let img = document.getElementById("imgClickAndChange");
let newIndex = currentIndex + dir;
currentIndex = images[newIndex] != undefined ? newIndex : (dir > 0 ? 0 : images.length-1);
// Change the picture
img.src = images[currentIndex];
// Change the description
document.getElementById("description").innerHTML = descriptions[currentIndex];
}
document.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == '37') {
changeImage(-1) //left <- show Prev image
} else if (e.keyCode == '39') {
// right -> show next image
changeImage(1)
}
}
Here is the example code:
https://jsfiddle.net/fwgk7stt/

Keydown event does not fire a function

I've made a simple code which should change visibility of box while certain key is pressed,but something is wrong because whichever button will be pressed it always says it's wrong.
This should work only while "f" key is pressed,right now it doesn't work at all...
const brick = document.querySelector('.brick');
window.addEventListener('keydown',function(e)
{
e.preventDefault();
if(e.keycode == 70)
{
let x = event.keyCode;
console.log(x);
brick.style.visibility = "visible";
} else {
let x = e.keyCode;
console.log(x);
console.log("You've pressed wrong button")
brick.style.visibility ="hidden";
}
});
Code is Here
I know i can use jquery but i would like to do this in pure JS
Greets
Slight syntax error:
if(e.keycode == 70)
should be:
if(e.keyCode == 70)
Notice the capital C.
This may helpful . After run the code press key "F" in the keyboard to see the red div
const brick = document.querySelector('.brick');
window.addEventListener('keydown',function(e)
{
e.preventDefault();
let x = e.keyCode;
if(x == 70)
{
//console.log(x);
brick.style.visibility = "visible";
}
else
{
//console.log(x);
//console.log("You've pressed wrong button")
brick.style.visibility ="hidden";
}
});
.brick
{
width:100px;
height:100px;
visibility: hidden;
background-color: red;
display:block;
}
<div class="brick" >
</div>

Javascript not closing menu

I have a piece of JavaScript which I use to search my site. When you type into the search it pulls up the products matching you query. This works fine, but I want the dropdown to close when the user clicks on the page. I know very little about JavaScript so any advice or even a point in the right direction will be appreciated.
function showSmartSearch() {
$.ajax({
url: "index.php?route=product/ajaxsearch&search=" + $("input[name='search']").val(),
type: "GET",
success: function(e) {
$("#smartsearchdiv").css("display", "block");
var t = "";
$("#smartsearchdiv").html(e)
}
})
}
function hideSmartSearch() {
$("#smartsearchdiv").css("display", "none")
}
var wait;
$(document).ready(function() {
$("input[name='search']").after('<div id="smartsearchdiv" style="margin-top:30px;background:white;width:230px;position:absolute;z-index:999;"></div>').blur(function() {}).keydown(function(e) {
if ($("input[name='search']").length && e.which == 38) {
e.preventDefault();
return false
}
}).keyup(function(e) {
if (!$("input[name='search']").val()) {
$("#smartsearchdiv").css("display", "none")
}
var t = $("input[name='search']").val();
var n = t.length;
if (t.replace(/^\s+|\s+$/g, "") && (e.which == 8 || 47 < e.which && e.which < 112 || e.which > 185)) {
if (n > 0) {
showSmartSearch()
} else {
hideSmartSearch()
}
}
if ($("#smartsearchdiv li").length && (e.which == 38 || e.which == 40)) {}
}).blur(function() {})
});
function hideSmartSearch() {
$("#smartsearchdiv").css("display", "none");
}
You can try this:
$(document).click(function(e){ // hide list if clicked outside
if($(e.target).is('#smartSearchDiv, #smartSearchDiv *'))return;
hideSmartSearch();
});
Also this:
$(document).click(function(e){ // hide list if clicked outside
if(!$(e.target).is('#smartSearchDiv'))
hideSmartSearch();
});
Use this:
$("#smartSearchDiv").click(function(e){
e.stopPropagation();
});
$(body).click(function(){
if($("#smartSearchDiv").is(":visible")){
hideSmartSearch();
}
});
This way, if you click on your search div, event will stop propagation to its parents, and nothing will happen. Otherwise, it will go upto your body and fire a close function.

wait till function execute completely to execute the other

I have this jquery code to handle some cases if user clicked right or left button but the navigate became a mess when the user click both buttons together
$(document).ready(function(){
$(document).keydown(function(e){
if (e.keyCode == 37) {
setTimeout(LeftKeyPressed(),5000);
}
else if(e.keyCode == 39){
setTimeout(RightKeyPressed(),5000);
}
});
});
I want to simply block any call till the first or second function completely executed
Use a flag to block the unnecessary function calls like this,
$(document).ready(function(){
var xKeyPressed = false;
$(document).keydown(function(e){
if (e.keyCode == 37 && !xKeyPressed) {
setTimeout(LeftKeyPressed(),5000);
}
else if(e.keyCode == 39 !xKeyPressed){
setTimeout(RightKeyPressed(),5000);
}
});
function LeftKeyPressed()
{
xKeyPressed = true;
//Your code
xKeyPressed = false;
}
function RightKeyPressed(){
xKeyPressed = true;
//Your code
xKeyPressed = false;
}
});
Set a simple check if your code is running LeftKeyPressed or RightKeyPressed like this:
var inFunction = false;
$(document).ready(function(){
$(document).keydown(function(e){
if (e.keyCode == 37 && !inFunction) {
inFunction = true;
setTimeout(LeftKeyPressed(),5000);
}
else if(e.keyCode == 39 && !inFunction){
inFunction = true;
setTimeout(RightKeyPressed(),5000);
}
});
});
//Add this in your functions, both Left and Right variants,
function LeftKeyPressed(){
//Do your normal stuff here
inFunction = false;
}
There is other ways of doing this as well, but this is in my opinion a clear and concise way of doing it. You can potentially get race conditions with this approach.
$(document).ready(function(){
var navt;
$(document).keydown(function(e){
if(navt != null) return;
if (e.keyCode == 37) {
navt = setTimeout(function(){ LeftKeyPressed(); navt = null; },5000);
}
else if(e.keyCode == 39){
navt = setTimeout(function(){ RightKeyPressed(); navt = null; },5000);
}
});
});

How to limit Tab listener to callback only if the textbox has change

I'm trying to implement a Tab key listener for a textbox.
$('#mytextbox').live('keydown', function (e) {
if (e.keyCode == 9 || e.which == 9) {
// TO DO SOMETHING
}
});
However, for some reason I need to limit the tab listener's callback to invoke only when the textbox has changed. Is there anyway to do this?
You might be able to check the value of the input field to make sure it's different from it's original value?
E.g.
$('#mytextbox').live('keydown', function (e) {
if ((e.keyCode == 9 || e.which == 9) && ($('#TextBox').val() != 'Starting Value')) {
// TO DO SOMETHING
}
});
You can do it just like:
var data = "";
$('#mytextbox').live('keydown', function (e){
if(e.which == 9 || e.keyCode == 9){
if($(this).val() != data){
alert('changed!');
data = $(this).val();
}
}
});
http://jsfiddle.net/DDCZS/1/
Or without storing / knowing value of that textbox:
var changed = false;
$('#mytextbox').on('keydown', function (e) {
if (e.which == 9 && changed) {
e.preventDefault();
// TO DO SOMETHING
alert("works");
changed = false;
} else {
changed = true;
}
});
http://jsfiddle.net/9a37b/

Categories