Change Font Awesome Icon Only - javascript

I am trying to change the icon from chevron-down to chevron-up when clicked. Currently, it shows "Categories" and "Hide" when clicked. I would like to have it say "Categories" the whole time. Is that possible?
Here is the code:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<h1 onclick="arata_ascunde(this);" class="btn btn-info " id="show_hide_bt">
<i class="fa fa-chevron-down"></i> Categories
</h1>
<div id="showhide" style="display:none;">
<ul>
<li>Hello World
</li>
</ul>
</div>
JS
function arata_ascunde(h1) {
var x = $('#showhide');
$(h1).find('i').remove();
if ($(h1).text().trim() == 'Categories') {
$(h1).html($('<i/>',{class:'fa fa-chevron-up'})).prepend('Hide ');
x.fadeIn();
}
else {
$(h1).html($('<i/>',{class:'fa fa-chevron-down'})).prepend('Categories ');
x.fadeOut();
}
}
CodePen: https://codepen.io/chadwicked123/pen/porRoOq

Your "if condition" is on something that can't be detected if it will be the same in all conditions. So it's better to change your condition to something more specific, like the tag's class. like this :
function arata_ascunde(h1) {
var x = $('#showhide');
if ($(h1).find('i').hasClass('fa-chevron-down')) {
$(h1).find('i').remove();
$(h1).html($('<i/>',{class:'fa fa-chevron-up'})).append(' Categories');
x.fadeIn();
} else {
$(h1).find('i').remove();
$(h1).html($('<i/>',{class:'fa fa-chevron-down'})).append(' Categories');
x.fadeOut();
}
}
I changed a few things to make your result more beautiful. This code still can be improved (I'm not a front-end developer).

I used basic javascript and some logic to change the HTML based on a class
Here's the codepen for it - Link
Here's the edited JS file :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<h1 onclick="arata_ascunde(this);" class="btn btn-info " id="show_hide_bt">
Categories<i class="fa fa-chevron-down"></i>
</h1>
<div id="showhide" style="display:none;">
<ul>
<li>Hello World
</li>
</ul>
</div>
and the edited JS file
function arata_ascunde(h1) {
var x = $('#showhide');
$(h1).find('i').remove();
if (document.querySelector("h1").classList.contains("down")) {
$(h1).html($('<i/>',{class:'fa fa-chevron-up'})).prepend('Categories ');
document.querySelector("h1").classList.remove("down")
x.fadeIn();
}
else {
$(h1).html($('<i/>',{class:'fa fa-chevron-down'})).prepend('Categories ');
document.querySelector("h1").classList.add("down")
x.fadeOut();
}
}

Related

jQuery: change link text and icon on click

So I am trying to change the the icon of my link for collapse section alongside with the text of the link.
Here is my code:
<a href="#collapse", class="btn", role="button", data-bs-toggle="collapse" id="btn-collapse">
<i class="material-icons" style="vertical-align: middle;">expand_more</i>
<label style="vertical-align: middle;">PRIMARY TEXT</label>
</a>
<!--CONTENT-->
<script>
$(document).ready(function(){
$('#btn-collapse').on('click', function () {
var text=$('#btn-collapse').text();
if(text === "SECONDARY TEXT"){
$(this).text('PRIMARY TEXT');
$(this).find("i").html("expand_more");
} else{
$(this).text('SECONDARY TEXT');
$(this).find("i").html("expand_less");
}
});
});
</script>
I've been trying to find a solution for this for a while now, but nothing seems to work.. Text changes fine, but the icon completely vanishes on click. I don't think it is a major issue, but there is something I don't get with this. Any help here how to adjust?
$(document).ready(function() {
$('#btn-collapse').on('click', function() {
var thisElement = $(this);
var anchorLabelElement = thisElement.find('label');
if (anchorLabelElement.text() === "SECONDARY TEXT") {
anchorLabelElement.text('PRIMARY TEXT');
thisElement.find("i").text('expand_more');
} else {
anchorLabelElement.text('SECONDARY TEXT');
thisElement.find("i").text("expand_less");
}
});
});
<link href="https://cdn.jsdelivr.net/npm/material-design-icons-iconfont#6.7.0/dist/material-design-icons.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#collapse" , class="btn" , role="button" , data-bs-toggle="collapse" id="btn-collapse">
<i class="material-icons" style="vertical-align: middle;">expand_more</i>
<label style="vertical-align: middle;">PRIMARY TEXT</label>
</a>

When I load two identical (confirmed by IntelliJ) JS scripts into my web app one produces different results than the other

TL;DR: IntelliJ confirms to different scripts are identical, but they produce different results when ran in the browser (using IntelliJ with Tomcat). Exact details below.
I am creating a web project using Spring MVC that allows me to play chess. I am using the chess.js library and the chessboard.js library.
According to the chess.js library README, it has a methodpgn() that returns the moves of the game as a string. You can optionally pass in a JSON to set a max_length and a newline character so that there is a new line character after black moves. For example game.pgn({ max_width: 5, newline_char: '<br />' }).
Here's my problem. I made a script called initgame.js that instantiates a chess game using the libraries and attempted to use the example above so that the moves printed out would be formatted to print a new line after each turn.
It wasn't working as I had hoped. So I created another script test_game.js to experiment and when I got the behavior I wanted I copy and pasted the contents of test_game.js into initgame.js. Changed the <script> tag point to initgame.js again and it was ignoring the line breaks again. Used IntelliJ to compare the files and IntelliJ confirms that the files are indeed identical.
Now I am just dumbfounded. I tried rebuilding the project, cleaning the Artifacts, cleaning Maven. Nothing. I even closed out of IntelliJ and restarted. When I run the program with test_game.js it works as desired. When I run it with initgame.js it ignores the line breaks.
As a potential hint, this doesn't happen when I use Visual Studio and load it into the browser as an .html instead of a .jsp Any insight is appreciated! Code and screen shots of output are below as well as a screen shot IntelliJ comparing the files.
initgame.js
// NOTE: this example uses the chess.js library:
// https://github.com/jhlywa/chess.js
var board = null;
const game = new Chess()
var $status = $('#status');
var $fen = $('#fen');
var $pgn = $('#pgn');
function onDragStart (source, piece, position, orientation) {
// do not pick up pieces if the game is over
if (game.game_over()) return false;
// only pick up pieces for the side to move
if ((game.turn() === 'w' && piece.search(/^b/) !== -1) ||
(game.turn() === 'b' && piece.search(/^w/) !== -1)) {
return false
}
}
function onDrop (source, target) {
// see if the move is legal
var move = game.move({
from: source,
to: target,
promotion: 'q' // NOTE: always promote to a queen for example simplicity
});
// illegal move
if (move === null) return 'snapback';
updateStatus()
}
// update the board position after the piece snap
// for castling, en passant, pawn promotion
function onSnapEnd () {
board.position(game.fen())
}
function updateStatus () {
var status = '';
var moveColor = 'White';
if (game.turn() === 'b') {
moveColor = 'Black'
}
// checkmate?
if (game.in_checkmate()) {
status = 'Game over, ' + moveColor + ' is in checkmate.'
}
// draw?
else if (game.in_draw()) {
status = 'Game over, drawn position'
}
// game still on
else {
status = moveColor + ' to move';
// check?
if (game.in_check()) {
status += ', ' + moveColor + ' is in check'
}
}
$status.html(status);
$fen.html(game.fen());
$pgn.html(game.pgn({ max_width: 5, newline_char: '<br />' }))
}
var config = {
draggable: true,
position: 'start',
onDragStart: onDragStart,
onDrop: onDrop,
onSnapEnd: onSnapEnd
};
board = Chessboard('myBoard', config);
updateStatus();
test_game.js
// NOTE: this example uses the chess.js library:
// https://github.com/jhlywa/chess.js
var board = null;
const game = new Chess()
var $status = $('#status');
var $fen = $('#fen');
var $pgn = $('#pgn');
function onDragStart (source, piece, position, orientation) {
// do not pick up pieces if the game is over
if (game.game_over()) return false;
// only pick up pieces for the side to move
if ((game.turn() === 'w' && piece.search(/^b/) !== -1) ||
(game.turn() === 'b' && piece.search(/^w/) !== -1)) {
return false
}
}
function onDrop (source, target) {
// see if the move is legal
var move = game.move({
from: source,
to: target,
promotion: 'q' // NOTE: always promote to a queen for example simplicity
});
// illegal move
if (move === null) return 'snapback';
updateStatus()
}
// update the board position after the piece snap
// for castling, en passant, pawn promotion
function onSnapEnd () {
board.position(game.fen())
}
function updateStatus () {
var status = '';
var moveColor = 'White';
if (game.turn() === 'b') {
moveColor = 'Black'
}
// checkmate?
if (game.in_checkmate()) {
status = 'Game over, ' + moveColor + ' is in checkmate.'
}
// draw?
else if (game.in_draw()) {
status = 'Game over, drawn position'
}
// game still on
else {
status = moveColor + ' to move';
// check?
if (game.in_check()) {
status += ', ' + moveColor + ' is in check'
}
}
$status.html(status);
$fen.html(game.fen());
$pgn.html(game.pgn({ max_width: 5, newline_char: '<br />' }))
}
var config = {
draggable: true,
position: 'start',
onDragStart: onDragStart,
onDrop: onDrop,
onSnapEnd: onSnapEnd
};
board = Chessboard('myBoard', config);
updateStatus();
.jsp page
<!doctype html>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet"
href="${pageContext.request.contextPath}/static/javascript/chessboardjs/css/chessboard-1.0.0.min.css">
<link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/bootstrap.min.css">
<title>Hello, world!</title>
</head>
<body>
<main>
<div class="container">
<div class="d-flex justify-content-between align-items-center">
<h1>Hello World</h1>
Login
</div>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">
<i class="fas fa-chess-queen"></i>
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<!-- Replace with Spring security Login form -->
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<div class="container">
<div class="row justify-content-center mx-1 my-3">
<div id="myBoard" class="col-6"></div>
<div class="card bg-light col-3">
<div class="card-header">Header</div>
<div class="card-body">
<h5 class="card-title">PGN</h5>
<p class="card-text">Here are the moves of the game as printed by test_game.js</p>
<div class="card-text" id="pgn"></div>
</div>
<button type="button" class="btn btn-primary m-3">Reset Game</button>
</div>
</div>
<div class="row justify-content-center">
<label>Status:</label>
<div id="status"></div>
<label>FEN:</label>
<div id="fen"></div>
<!--
<label>PGN:</label>
<div id="pgn"></div> -->
</div>
</div>
</div>
</main>
<%-- jquery --%>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>
<script src="${pageContext.request.contextPath}/static/javascript/chessboardjs/js/chessboard-1.0.0.min.js"></script>
<script src="${pageContext.request.contextPath}/static/javascript/node_modules/chess.js/chess.js"></script>
<script src="${pageContext.request.contextPath}/static/javascript/test_game.js"></script>
</body>
</html>
With initgame.js
With test_game.js
The results of the IntelliJ compare function
try this : replace
$pgn.html(game.pgn({ max_width: 5, newline_char: '<br />' c}))
by
var pgnn = game.pgn({ max_width: 5, newline_char: '<br />' })
pgnn = pgnn + " </br>"
$pgn.html(pgnn)
i'm not sure that it gonna work but i think

Why is my <i> tag being appended multiple times for each click as I click the add button?

I am making a Todo list using HTML, CSS and jQuery. So basically when the person types an activity and presses the '+' button it gets added to the list along with a 'Delete'(Font Awesome Recycle Bin) icon so that the user can delete the activity. I have implemented this using the .append() function. However, when a user adds the first item there is one delete button. However for every other list the number of delete buttons multiply. (Eg. when the user adds the second item there are two delete buttons for that item, and when they add the third item there are three delete buttons for that item). I can't understand why this is happening and what is the best way to fix this?
I have used .append() on the .listInput and appended the .newItem.
I have then used .append() on the .newItem and appended the can icon.
$(".enter").click(function() {
var $item = $('input[name=add]').val();
if ($item.length > 0) {
$(".listInput").append('<li class="newItem animated fadeIn">' + $item + '</li>');
$('.newItem').append('<i class="animated fadeIn far fa-trash-alt fa-1x"></i>');
} else {
alert("Enter an acitvity to add");
}
})
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="takeInput">
<input type="text" name="add" value="Add Your Item Here">
<i class="enter fas fa-plus fa-3x"></i>
</div>
<ul class="listInput">
</ul>
I want only one trash icon for each list item.
$('.newItem').append() will append something to all elements with the class newItem, not just the one you just added. To fix that just use a single append:
$(".enter").click(function() {
var $item = $('input[name=add]').val();
if ($item.length > 0) {
$(".listInput").append('<li class="newItem animated fadeIn">' + $item + '<i class="animated fadeIn far fa-trash-alt fa-1x"></i></li>');
} else {
alert("Enter an acitvity to add");
}
})
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="takeInput">
<input type="text" name="add" value="Add Your Item Here">
<i class="enter fas fa-plus fa-3x"></i>
</div>
<ul class="listInput">
</ul>
Please try this
var $item = $('input[name="add"]').val();
The problem is that $('.newItem') refers to any element that has that class. For example, if you have five items on the list they will all have the class new item. If you were to add another item (that makes six items), then you are adding a bin icon to each element with class 'newItem'
$(".enter").click(function() {
var $item = $('input[name=add]').val();
if ($item.length > 0) {
$(".listInput").append('<li class="newItem animated fadeIn">' + $item + '</li>' + '<i class="animated fadeIn far fa-trash-alt fa-1x"></i>');
} else {
alert("Enter an acitvity to add");
}
})
$(".enter").click(function() {
let item = $('input[name=add]').val();
let li = $('<li class="newItem animated fadeIn"/>');
let iconTrash = $('<i style="margin-left:1em;" class="animated fadeIn far fa-trash-alt fa-1x"/>')
if (item.length >= 0) {
li.append(item,iconTrash)
$(".listInput").append(li);
} else {
alert("Enter an acitvity to add");
}
})
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="takeInput">
<input type="text" name="add" value="Add Your Item Here">
<i class="enter fas fa-plus fa-3x"></i>
</div>
<ul class="listInput">
</ul>
The problem is the trash icon is added to all the elements that have the class 'newItem'. So you have to create a li(list item) element and append it to the ul(unordered list) element. Then create the icon and append it to the created list item element. You can create element using the document.createElement(tagName) function. and append it using javascript or jquery

JQuery toggle() html data

I have tried searching for a solution to this but can't seem to find a working answer. I may have missed something obvious.
I have a link to show the latest comments on a status. When the link is clicked the link data changes to "Close" (all good) but when close is then clicked to toggle the DIV the link data stays "Close", I want it to return to the original text (i.e 3 Comments).
The HTML:
<a class="comments" id="coms-<?php echo $statmainID; ?>" href="javascript:;"><i class="fa fa-comment"></i> <?php echo $numComs; ?> Comments</a>
<div id="comss<?php echo $statmainID; ?>" style="display:none;">Comments Here</div>
The JQuery:
$(function(){
$('body').on('click', '.comments', function(){
var cID =$(this).attr('id');
var theID = cID.split("-");
var divID = theID[1];
$('#comss'+divID).toggle("slide");
$('.comments'+divID).html('Close');
return false;
});
});
As always, any help from you guru's is always appreciated.
Kind regards.
You can use data attribute to store the original text. Then you can show it again.
HTML
<body>
<a class="comments" id="coms-1" href="javascript:;" data-id="comss1" data-text="4 Comments">
<i class="fa fa-comment"></i> 4 Comments
</a>
<div id="comss1" style="display:none;">Comments Here</div>
<a class="comments" id="coms-2" href="javascript:;" data-id="comss2" data-text="2 Comments">
<i class="fa fa-comment"></i> 2 Comments
</a>
<div id="comss2" style="display:none;">Comments Here</div>
</body>
JS
$(function(){
$('body').on('click', '.comments', function(){
var cID =$(this).attr('id');
var theID = cID.split("-");
var divID = theID[1];
$('#comss'+divID).toggle("slide");
var comments = $('#coms-'+divID);
if($(comments).text() === "Close"){
$(comments).html($(comments).data("text"));
} else {
$(comments).html('Close');
}
return false;
});
});
WORKING FIDDLE
var prevText=$(".comments").text();
$(".comments").click(function(){
if($(this).text().indexOf("Comments")>=0){
$(this).text("Close");
}
else
{
$(this).text(prevText);
}
return false;
});
UPDATE
FIDDLE WITH STATIC NUMBER OF COMMENTS
You can do it like following. Keep the original text in a data attribute and show it when on Close click.
$('body').on('click', '.comments', function() {
var cID = $(this).attr('id');
var theID = cID.split("-");
var divID = theID[1];
$('#comss' + divID).toggle("slide");
if ($(this).html().trim() != 'Close') {
$(this).data('text', $(this).html());
$(this).html('Close');
} else {
$(this).html($(this).data('text'));
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.css" />
<a class="comments" id="coms-1" href="javascript:;"><i class="fa fa-comment"></i> 1 Comments</a>
<div id="comss1" style="display:none;">Comments Here</div>

Boot strap button group change jQuery

Im starting to learn JavaScript/jQuery and have the code below that works but there must be some shorter code to write for this simple function.
The function:
Font awesome icon to show and change when i choose access level in the boot strap button group.
$(document).ready(function() {
$("#access").html(' Alla');
$("#accessIcon").addClass('fa-globe');
$('#access_input').val(0);
});
/*
' access
' 0 = all
' 1 = friends
' 2 = private
*/
$(".access").click(function(e) {
var accessId = $(this).attr('id');
if (accessId == 0) {
//alert("Alla = "+ accessId);
$("#access").html(' Alla');
$("#accessIcon").removeClass('fa-group');
$("#accessIcon").removeClass('fa-eye');
$("#accessIcon").addClass('fa-globe');
$('#access_input').val(accessId);
} else if (accessId == 1) {
//alert("Vänner = "+ accessId);
$("#access").html(' Vänner');
$("#accessIcon").removeClass('fa-globe');
$("#accessIcon").removeClass('fa-eye');
$("#accessIcon").addClass('fa-group');
$('#access_input').val(accessId);
} else if (accessId == 2) {
//alert("Privat = "+ accessId);
$("#access").html('Privat');
$("#accessIcon").removeClass('fa-globe');
$("#accessIcon").removeClass('fa-group');
$("#accessIcon").addClass('fa-eye');
$('#access_input').val(accessId);
} else {
alert("inget alternativ valt! = " + accessId);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<!-- Start inputs -->
<input type="text" id="access_input" value="">
<br>
<div class="btn-group">
<button type="button" class="btn btn-default"><i id="accessIcon" class="fa "> </i> <span id="access">Action</span>
</button>
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu">
<li><i class="fa fa-globe"></i> Alla
</li>
<li><i class="fa fa-group"></i> Vänner
</li>
<li><i class="fa fa-eye"></i> Privat
</li>
</ul>
</div>
Add to each links with class 'access' data attributes first for icon class name and second for title. Example for first link:
<a href="javascript:void(0);" class="access" id="0" data-icon="globe" data-title="Alla">
And your onclick can be simplified to:
$(".access").click(function(e) {
$("#access").html($(this).data('title'));
$("#accessIcon").removeClass();
$("#accessIcon").addClass('fa fa-' + $(this).data('icon'));
$('#access_input').val($(this).attr('id'));
});
Well, for starters, I would extract the UI details that are buried deep in your conditions, so that you may use variables instead:
var accessTypes = [
{ title: 'Alla', icon: 'fa-globe' },
{ title: 'Vänner', icon: 'fa-group' },
{ title: 'Privat', icon: 'fa-eye' }
];
Then you could simply do:
$(".access").click(function(e) {
var accessId = $(this).attr('id');
var access = accessTypes[accessId];
$("#access").html(' ' + access.title);
$("#accessIcon").attr('class', 'fa ' + access.icon);
$('#access_input').val(accessId);
});
Note that this works only because the id of your buttons are matching the array index in accessTypes. This solution will break down once you add a second set of buttons for something else.
I would suggest that you move away from relying on id to a data attribute for this purpose, and I would also use string identifiers, although doing just either one of them would be sufficient to solve the problem.
<a href="javascript:void(0);" class="access" data-id="all"> <!-- etc -->
You would then use:
var accessTypes = {
all: { title: 'Alla', icon: 'fa-globe' },
friends: { title: 'Vänner', icon: 'fa-group' },
'private': { title: 'Privat', icon: 'fa-eye' }
};
And...
$(".access").click(function(e) {
var accessId = $(this).data('id');
var access = accessTypes[accessId];
...
});

Categories

Resources