onkeydown navigate forward and backward with arrows key - javascript

I try to navigate onkeydown with the arrow keys left and right throw my website.
With my font awesome links it is working, but I want that it also works onkeydown with the arrow keys on my keyboard.
One problem is, that my site use localization for german an english. That is why my url's look like this:
https://www.example.com/de
https://www.example.com/en
https://www.example.com/de/Arbeiten
https://www.example.com/en/Projects
Here is my HTML:
<div>
<a href="{{ route('contact') }}" onkeydown="if(e.keyCode == 37) ? window.location.href={{ route('contact') }} : " class="left-arrow arrow-home-left">
<i class="fas fa-angle-left fa-5x"></i>
</a>
</div>
<div>
<a href="{{ route('projects') }}" onkeydown="if(e.keyCode == 39) ? window.location.href={{ route('projects') }} : " class="right-arrow arrow-home-right">
<i class="fas fa-angle-right fa-5x"></i>
</a>
</div>
And my CSS:
body {
background-color: green;
}
.arrow-home-right {
display: inline;
top: 50%;
right: 0;
color: white;
background-color:red;
position: fixed;
}
.arrow-home-left {
display: inline;
top: 50%;
left: 0;
color: white;
background-color:red;
position: fixed;
}
.arrow-home-right:hover, .arrow-home-left:hover {
display: inline;
color: black;
}
Here is my JSFiddle:
https://jsfiddle.net/djosxy7z/15/
I want to jump to the next site/page with the arrow keys onkeydown. With the font awesome links it is working, but not wit the keyboard.
Hope, somone can give me a hint. :)
e: Do I have to call the onkeydown function on the body?

You can capture the keydown event with your body tag. Here is an example:
<body onload="onload_handler()">
<div>
<a href="{{ route('contact')}}" class="left-arrow arrow-home-left">
<i class="fas fa-angle-left fa-5x"></i>
</a>
</div>
<p></p>
<div>
<a href="{{ route('projects')}}" class="right-arrow arrow-home-right">
<i class="fas fa-angle-right fa-5x"></i>
</a>
</div>
<script>
function onload_handler() {
document.body.addEventListener("keydown", keydown_handler);
}
function keydown_handler(e) {
let txt = "keydown_handler: keycode = " + e.keyCode;
let anchor = 0;
if(e.keyCode == 37) {
anchor = document.body.querySelector(".left-arrow")
txt = txt + ": left arrow";
} else if(e.keyCode == 39) {
anchor = document.body.querySelector(".right-arrow")
txt = txt + ": right arrow";
}
if(anchor)
txt = txt + ": " + anchor.href;
console.log(txt);
if(anchor)
anchor.click();
}
</script>
</body>
Here is a link to the same site that you posted your fiddle on, using the example above. The example shows which keys you press in the console.

Related

jQuery css() not applying [duplicate]

This question already has answers here:
How to apply !important using .css()?
(31 answers)
Closed 1 year ago.
<img id="icon-img" src="assets/img/tabicon2.png" class="position-absolute top-50 start-50 translate-middle" style="max-width:113px; top: 43%!important; z-index:0;" alt="">
<a id="savethepub" class="tab-base navbar-brand navbar-brand position-absolute top-50 start-50 translate-middle" style="top: 84%!important; font-size:22px;" href="#">Save The British Pub</a>
I am having an issue with JQuery, my code above is the HTML and is all correct, and the code below targets a button on the page. I have checked using test and the button works however the CSS isnt applying.
var button = $( "#collapser" );
var tabimg = $( "#icon-img" );
var stp = $( "#savethepub" );
var bntclicked = false;
button.click(function() {
if (bntclicked === false) {
tabimg.css({"max-width":"70px", "top":"8%!important", "left":"21%!important", "z-index":"0"})
stp.css({"font-size":"22px", "top":"7%!important"})
bntclicked = true;
}
else if (bntclicked === true) {
tabimg.css({"max-width":"113px", "top":"43%!important", "left":"50%!important", "z-index":"0"})
stp.css({"font-size":"22px", "top":"84%!important"})
bntclicked = false;
}
});
Button Code:
<button id="collapser" class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
The issue is because you've included the !important flag in the values of the CSS properties in the object you provide to css(). These are invalid and need to be removed.
You also need to remove the !important flag on the inline styles you have added in the HTML, as they are entirely redundant. Inline styles have the highest precedence so !important has no effect there, unless you've included !important somewhere else in your stylesheets, which again means that should be removed.
The !important flag should be avoided where possible, in favour of using selector precedence. The only real legitimate use for it is when you're attempting to override styles applied by a third party source which you have no control over - and even then rule precedence should be the primary solution.
Try the following example:
var button = $("#collapser");
var tabimg = $("#icon-img");
var stp = $("#savethepub");
var bntclicked = false;
button.click(function() {
if (bntclicked === false) {
tabimg.css({
"max-width": "70px",
"top": "8%",
"left": "21%",
"z-index": "0"
});
stp.css({
"font-size": "22px",
"top": "7%"
})
bntclicked = true;
} else if (bntclicked === true) {
tabimg.css({
"max-width": "113px",
"top": "43%",
"left": "50%",
"z-index": "0"
});
stp.css({
"font-size": "22px",
"top": "84%"
});
bntclicked = false;
}
});
#icon-img { position: absolute; }
#savethepub { position: absolute; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="collapser">Collapser</button>
<a href="https://www.timeatthebar.co.uk" target="_blank">
<img id="icon-img" src="assets/img/tabicon2.png" class="position-absolute top-50 start-50 translate-middle" style="max-width: 113px; top: 43%; z-index: 0;" alt="">
</a>
<a id="savethepub" class="tab-base navbar-brand navbar-brand position-absolute top-50 start-50 translate-middle" style="top: 84%; font-size: 22px;" href="#">Save The British Pub</a>
However it should be noted that the logic can be made much simpler if you use classes to apply the styling. The JS logic to update the styling effectively then becomes a single line:
var $button = $("#collapser");
var $tabimg = $("#icon-img");
var $stp = $("#savethepub");
$button.on('click', () => {
$tabimg.add($stp).toggleClass('active');
})
#icon-img {
position: absolute;
max-width: 113px;
top: 43%;
z-index: 0;
}
#icon-img.active {
max-width: 70px;
top: 8%;
left: 21%;
}
#savethepub {
position: absolute;
top: 84%;
font-size: 22px;
}
#savethepub.active {
top: 7%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="collapser">Collapser</button>
<a href="https://www.timeatthebar.co.uk" target="_blank">
<img id="icon-img" src="assets/img/tabicon2.png" class="position-absolute top-50 start-50 translate-middle" alt="">
</a>
<a id="savethepub" class="tab-base navbar-brand navbar-brand position-absolute top-50 start-50 translate-middle" href="#">Save The British Pub</a>
The reason this is failing is because you are trying to add the !important in the CSS function, and that's not allowed. To make this work as you would like you have a couple options. You could put the desired CSS in a class and then toggle the class (This is what I'd do). Another option is you could use the .attr() function to modify the style attr as a whole. One other option is to use the cssText selector, which allows you to add multiple CSS rules with one key. Example below:
// Change width
$('#txt').css({
'cssText': 'width: 220px !important; font-size: 12px;'
});
Here's a link to help: https://makitweb.com/how-to-add-important-to-css-property-with-jquery/
Here's your code with the !important taken out:
button.click(function() {
if (bntclicked === false) {
tabimg.css({"max-width":"70px", "top":"8%", "left":"21%", "z-index":"0"})
stp.css({"font-size":"22px", "top":"7%"})
bntclicked = true;
}
else if (bntclicked === true) {
tabimg.css({"max-width":"113px", "top":"43%", "left":"50%", "z-index":"0"})
stp.css({"font-size":"22px", "top":"84%"})
bntclicked = false;
}
});

i want to create clicked face is marked and other faces are default color on second click

I have a feed back section where once a face is clicked it is marked with a specific color and other faces are defaulted to a second color in case the user click on another face (if he changes his mind).
function feedback(tab_number) {
document.getElementById('feedback-' + tab_number).classList.add('clicked');
}
.feedback {
/*background-color: darkgray;*/
padding: 10px;
width: fit-content;
}
i {
margin: 10px;
/*color: gold;*/
}
.default {
color: black;
}
.clicked {
color: gold;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
<div class="feedback">
<i class="fas fa-angry fa-5x " id="feedback-1" onclick="feedback(1)"></i>
<i class="fas fa-frown-open fa-5x " id="feedback-2" onclick="feedback(2)"></i>
<i class="fas fa-smile fa-5x " id="feedback-3" onclick="feedback(3)"></i>
<i class="fas fa-grin-stars fa-5x " id="feedback-4" onclick="feedback(4)"></i>
</div>
Your question is not very clear, but I think you might mean something like:
function feedback(tab_number) {
let clicked = document.querySelector("i.clicked");
if (clicked) {
clicked.classList.remove("clicked");
}
document.getElementById("feedback-" + tab_number).classList.add("clicked");
}
.feedback {
/*background-color: darkgray;*/
padding: 10px;
width: fit-content;
}
i {
margin: 10px;
/*color: gold;*/
}
.default {
color: black;
}
.clicked {
color: gold;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
<div class="feedback">
<i class="fas fa-angry fa-5x " id="feedback-1" onclick="feedback(1)"></i>
<i class="fas fa-frown-open fa-5x " id="feedback-2" onclick="feedback(2)"></i>
<i class="fas fa-smile fa-5x " id="feedback-3" onclick="feedback(3)"></i>
<i class="fas fa-grin-stars fa-5x " id="feedback-4" onclick="feedback(4)"></i>
</div>
So, when you click on a different face, the previous highlighted face gets their clicked class removed from their class list and it gets added to the new clicked face's class list.
You can do it by checking if the element.classList.contains('clicked'). If it does, then it has already been clicked and then you need to remove the class clicked, otherwise add it.
See below:
Note: I've edited it further to provide functionality for removing and adding class clicked to other faces automatically.
function feedback(tab_number) {
let clickedElem = document.getElementById('feedback-' + tab_number);
let add = false;
if( !clickedElem.classList.contains('clicked') ) {
add = true;
}
let elems = document.querySelectorAll(".feedback i");
elems.forEach(function(el) {
let currTabNum = el.id.substr(9, el.id.length); // get the tab number
if(add && currTabNum <= tab_number) {
document.getElementById('feedback-' + currTabNum).classList.add('clicked');
} else if(!add && currTabNum >= tab_number) {
document.getElementById('feedback-' + currTabNum).classList.remove('clicked');
}
});
}
.feedback {
/*background-color: darkgray;*/
padding: 10px;
width: fit-content;
}
i {
margin: 10px;
/*color: gold;*/
}
.default {
color: black;
}
.clicked {
color: gold;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet"/>
<div class="feedback">
<i class="fas fa-angry fa-5x " id="feedback-1" onclick="feedback(1)"></i>
<i class="fas fa-frown-open fa-5x " id="feedback-2" onclick="feedback(2)"></i>
<i class="fas fa-smile fa-5x " id="feedback-3" onclick="feedback(3)"></i>
<i class="fas fa-grin-stars fa-5x " id="feedback-4" onclick="feedback(4)"></i>
</div>
Note:
Check this out:
function feedback(tab_number){
document.getElementById('feedback-1').classList.remove('clicked');
document.getElementById('feedback-2').classList.remove('clicked');
document.getElementById('feedback-3').classList.remove('clicked');
document.getElementById('feedback-4').classList.remove('clicked');
document.getElementById('feedback-' + tab_number).classList.add('clicked');
}
First, you need to know where you're going wrong:
You are dynamically fetching a HTMLElement by id, based on the value passed as the tab to your function. So when that element is fetched, you decorate it with a class clicked. The moment you click a different icon with a different tab number, the class clicked is not removed from the previous click. So Your DOM still has the class added based on the previous clicks.
I would approach this solution by doing the following.
// Get all Clickable Elements
var clickableElements = document.querySelectorAll('.clickable');
// Create a function that clears current state of the rating
function clearAllRatings(){
// Loop through each clickable rating and clear it's clicked class decoration
clickableElements.forEach(function(element)
{
element.classList.remove('clicked');
});
}
// Loop through each element
clickableElements.forEach(function(eachElement){
// Add Click event to each element
eachElement.addEventListener('click', function(event){
// clear current rating
clearAllRatings();
// creat new rating
event.target.classList.add('clicked');
});
});
.feedback {
/*background-color: darkgray;*/
padding: 10px;
width: fit-content;
}
i {
margin: 10px;
/*color: gold;*/
}
.default {
color: black;
}
.clicked {
color: gold;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet"/>
<div class="feedback">
<i class="fas fa-angry fa-5x clickable" id="feedback-1"></i>
<i class="fas fa-frown-open fa-5x clickable " id="feedback-2"></i>
<i class="fas fa-smile fa-5x clickable " id="feedback-3"></i>
<i class="fas fa-grin-stars fa-5x clickable " id="feedback-4"></i>
</div>

Change data status for all elements on click

In the first function, an item is marked read or unread by clicking the .activity__button. The next function is to change the status of all of the items to read.
Why isn't the function iterating over each item and button?
var button = $(".activity__button");
var item = $(".activity__item");
When I press the button to change the status to read, nothing happens. Additionally, how do you handle a second click of the button to change all back to unread?
$(".activity__button").on("click", function(e) {
e.stopPropagation();
e.preventDefault();
var icon = $(this).find("svg");
var status = $(this).attr("data-status");
if (status === "read") {
$(this)
.removeClass("activity__button--read")
.attr("data-status", "unread");
icon.attr("data-icon", "envelope");
$(this)
.closest(".activity__item")
.removeClass("activity__item--read")
.attr("data-status", "unread");
} else {
$(this)
.addClass("activity__button--read")
.attr("data-status", "read");
icon.attr("data-icon", "envelope-open");
$(this)
.closest(".activity__item")
.addClass("activity__item--read")
.attr("data-status", "read");
}
});
$(".section").on("click", ".mark", function(e) {
e.stopPropagation();
e.preventDefault();
var button = $(".activity__button");
var item = $(".activity__item");
var icon = button.find("svg");
var status = button.attr("data-status");
if (status === "unread") {
button.addClass("activity__button--read").attr("data-status", "read");
icon.attr("data-icon", "envelope-open");
item.addClass("activity__item--read").attr("data-status", "read");
}
});
.activity__item {
position: relative;
height: 100px;
width: 300px;
border: 1px solid whitesmoke;
margin-top: -1px;
}
.activity__button {
cursor: pointer;
padding: 1rem;
font-size: 21px;
}
.activity__button svg {
color: #f8971d;
}
.activity__button.activity__button--read svg {
color: #47a877;
}
.activity__item--read {
background: #fafafa !important;
}
button {
padding: 12px;
margin: 1rem;
}
<script src="https://pro.fontawesome.com/releases/v5.8.1/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class "section">
<button class="mark">Mark as Read</button>
<div>
<div class="activity__item">
<div class="activity__button" data-status="unread"><i class="fas fa-envelope"></i>
</div>
</div>
<div class="activity__item">
<div class="activity__button" data-status="unread"><i class="fas fa-envelope"></i>
</div>
</div>
<div class="activity__item activity__item--read">
<div class="activity__button activity__button--read" data-status="read">
<i class="fas fa-envelope-open"></i>
</div>
</div>
<div class="activity__item">
<div class="activity__button" data-status="unread">
<i class="fas fa-envelope"></i>
</div>
</div>
</div>
</div>
Working example (with other classes)
var open = 'fas fa-envelope-open';
var close = 'fas fa-envelope';
$(".activity__button").off().on('click', function() {
var status = $(this).data('status');
if( status == 'unread' ) {
$(this).data('status', 'read').empty().html('<i class="' + open + '"></i>').addClass('activity__button--read');
$(this).parent().addClass('activity__item--read');
} else {
$(this).data('status', 'unread').empty().html('<i class="' + close + '"></i>').removeClass('activity__button--read');
$(this).parent().removeClass('activity__item--read');
}
});
$('.mark').off().on('click', function() {
$(".activity__button").each( function() {
$(this).data('status', 'read').empty().html('<i class="' + open + '"></i>').addClass('activity__button--read');
$(this).parent().addClass('activity__item--read');
});
});
See here:
https://jsfiddle.net/8yk9a7rn/

javascript function that changes text on hover

I am using a slider using Slick and I want to change the left and right arrows text into (next and prev) after hovering on it. How can i do this using a javascript function ?
<div class="left-slider-arrow slider-arrow">
<i class="fa fa-chevron-left" aria-hidden="true"></i>
</div>
<div class="right-slider-arrow slider-arrow">
<i class="fa fa-chevron-right" aria-hidden="true"></i>
</div>
$(".left-slider-arrow").click(function(){
//now which text to change?
});
just edit slick-theme.css, watch line 89 and 107
.slick-next:before
{
content: '→';
}
[dir='rtl'] .slick-next:before
{
content: '←';
}
.slick-prev:before
{
content: '←';
}
[dir='rtl'] .slick-prev:before
{
content: '→';
}
replace '←' to "nedded text"...

toggle button with font awesome and jquery

I thought this was going to be simple, but I am having a bit of hard time getting this to work. I am able to toggle once using .show and .hide, but not able to toggle back.
all the help would be appreciated.
here is the code:
<div class="middle">
<i class="fa fa-toggle-on fa-2x active" id="on" style="display:none;"></i>
<i class="fa fa-toggle-on fa-2x fa-rotate-180 inactive" id="off" ></i>
</div>
$(document).ready(function(){
$('.middle').click(function(){
$('.inactive').show();
$('.active').hide();
})
.click(function(){
$('.inactive').hide();
$('.active').show();
});
});
I also have a pen of it here: http://codepen.io/lucky500/pen/qdZPLe
one approach is to use toggle
$(document).ready(function(){
$('.middle').click(function() {
$('.inactive, .active').toggle();
});
});
http://codepen.io/miguelmota/pen/zGqPOX
Why not simplify this a bit by using a single element with .toggleClass().
http://jsbin.com/ceyilucuya/1/edit?html,css,js,output
$('.toggler').on('click', function () {
$(this).toggleClass('fa-rotate-180 on');
});
The structure of your HTML it a little funky, however I found a dirty fix to your problem. The following code i repeat is a dirty fix, but it works.
http://codepen.io/anon/pen/MwyEdq
JS
$(document).ready(function(){
i = 0;
$(".fa-toggle-on").click(function() {
if ( i == 0) {
$('.inactive').hide();
$('.active').show();
i++;
}
else if ( i == 1) {
$('.inactive').show();
$('.active').hide();
i = 0;
}
});
});
HTML
<div class="middle">
<i class="fa fa-toggle-on fa-2x active" id="on" style="display:none;"></i>
<i class="fa fa-toggle-on fa-2x fa-rotate-180 inactive" id="off" ></i>
</div>
CSS
.middle {
text-align: center;
margin: 0 auto;
padding: 2rem;
}
.active {
color: green;
}
Generally and simply it works like this:
You can use this in general purposes.
<script>
$(document).ready(function () {
$('i').click(function () {
$(this).toggleClass('fa-plus-square fa-minus-square');
});
});
</script>
Rotating the fontawesome icon is a nice idea, however the browser may show some change in the vertical positioning since the icon has different transparent margins with respect to the visible pixels.
I combined the solutions of #miguel-mota and #oka.
Only one fontawesome tag is needed, the classes are switched in the on click function for the class .toggler.
Make sure to use the each function to apply multiple transformations.
JS
$('.toggler').on('click', function () {
$(".my-button").each(function(){
$(this).toggleClass('fa-toggle-off');
$(this).toggleClass('fa-toggle-on');
$(this).toggleClass('active');
})
});
CSS
.toggler {
text-align: center;
margin: 0 auto;
padding: 2rem;
cursor: pointer;
color: black;
}
.active {
color: green;
}
HTML
<div class="toggler">
<i class="fa fa-toggle-off fa-2x inactive my-button"></i>
</div>
This jQuery plugin worked well for me: https://github.com/hurkanaras/Hurkan-Switch-Plugin
An example:
$('[data-toggle="hurkanSwitch"]').hurkanSwitch({
'width':'90px',
'offConfirm': function(r) { return confirm('Are you sure you want to disable this?'); },
'on': function(e) { toggle(e, 'enable'); },
'off': function(e) { toggle(e, 'disable'); },
'onColor': 'green',
'offColor': 'red',
'className': 'switch-toggle' //I changed the font size with this
});
<head>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" >
</head>
<body>
<i id='checkboxAbcToggle' class='far fa-square cursorIcon'></i> Show Abc
</body>
=================
$('#checkboxAbcToggle').click(function () {
// Toaster.top('toggleClass');
UiUx.setCheckbox('#checkboxAbcToggle');
});
let Key = {
uncheckedSquare: 'fa-square',
checkedSquare: 'fa-check-square',
}
let UiUx = {};
UiUx.setCheckbox = function (checkboxIcon_jqId) {
let checkboxIconElement = $(checkboxIcon_jqId);
let isChecked = checkboxIconElement.hasClass(Key.checkedSquare);
if (isChecked === true) {
checkboxIconElement.removeClass(Key.checkedSquare);
checkboxIconElement.addClass(Key.uncheckedSquare);
}
else {
checkboxIconElement.removeClass(Key.uncheckedSquare);
checkboxIconElement.addClass(Key.checkedSquare);
}
}
css
.rotate{
transform:rotate(180deg);
color:black
}
jquery
$('.fa-toggle-on').on('click',function() {
$(this).toggleClass('rotate')
});

Categories

Resources