I have tooltips showing using data-toggle like in,
<i class="fa fa-fire fa-lg" data-toggle="tooltip" data-placement="bottom" title="Fire Place"></i>
I have styled the tooltips here using,
.tooltip > .tooltip-inner {
padding: 15px;
font-size: 120%;
background-color: #FFEB6C;
color: #374D40;}
I'd like tooltips on different places to look differentlylike the background color. i.e I want multiple looks for tooltips. but I don't see how I can set custom tooltip styles to each tooltip. I can't set a css class to each tooltip either since there's no such element,I'm setting tooltips through data-toggle.
Is there any way I can make this work? Thanks.
Simple, I created a class to hold those CSS style called custom-tooltip:
/* Tooltip */
.custom-tooltip+.tooltip>.tooltip-inner {
padding: 15px;
font-size: 1.2em;
background-color: #FFEB6C;
color: #374D40;
}
/* Tooltip on bottom */
.custom-tooltip+.tooltip.bottom>.tooltip-arrow {
border-bottom: 5px solid #FFEB6C;
}
$('i[data-toggle="tooltip"]').tooltip({
animated: 'fade',
placement: 'bottom'
});
/* Tooltip */
.custom-tooltip+.tooltip>.tooltip-inner {
padding: 15px;
font-size: 1.2em;
background-color: #FFEB6C;
color: #374D40;
}
/* Tooltip on top */
.custom-tooltip+.tooltip.top>.tooltip-arrow {
border-top: 5px solid #FFEB6C;
}
/* Tooltip on bottom */
.custom-tooltip+.tooltip.bottom>.tooltip-arrow {
border-bottom: 5px solid #FFEB6C;
}
/* Tooltip on left */
.custom-tooltip+.tooltip.left>.tooltip-arrow {
border-left: 5px solid #FFEB6C;
}
/* Tooltip on right */
.custom-tooltip+.tooltip.right>.tooltip-arrow {
border-right: 5px solid #FFEB6C;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<i class="fa fa-fire fa-lg custom-tooltip" data-toggle="tooltip" data-placement="bottom" title="Fire Place"></i>
I have prepared a quite universal solution for the bootstrap 3 tooltips' styling working with the dynamically created elements. It will work also in a case when a tooltip is generated not as a sibling to its element, but on a higher level of DOM, for example when a custom container option has been used:
<body>
<div>
<button type="button" class="btn btn-default" data-container="body" title="Tooltip text">Hover over me</button>
</div>
</body>
The tooltip's <div> will be generated there as a sibling to <div>, instead of <button>...
Solution
Let's make the template option of the Bootstrap tooltip object dynamic:
$.fn.tooltip.Constructor.prototype.tip = function () {
var template;
var $e = this.$element;
var o = this.options;
if (!this.$tip) {
template = typeof o.template == 'function' ? o.template.call($e[0]) : o.template;
this.$tip = $(template);
if (this.$tip.length != 1) {
throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!');
}
}
return this.$tip;
}
Prepare the tooltip template function. It will get all "tooltip-*" classes from the element with tooltip and append to the "tooltip-arrow" and "tooltip-inner" divs
tooltipTemplate = function () {
var classList = ($(this).attr('class')||"").split(/\s+/);
var filterTooltipPrefix = function(val){
return val.startsWith('tooltip-');
};
var tooltipClasses = classList.filter(filterTooltipPrefix).join(' ');
return '<div class="tooltip" role="tooltip"><div class="tooltip-arrow ' + tooltipClasses +'"></div><div class="tooltip-inner ' + tooltipClasses +'"></div></div>';
}
Ensure our function works in older browsers:
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position){
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
Now enable the tooltips:
$('body').tooltip({
selector: "[title]",
html: true,
template: tooltipTemplate
});
Example:
HTML
<h1>Test tooltip styling</h1>
<div><span title="Long-long-long tooltip doesn't fit the single line">Hover over me 1</span></div>
<div><span class="tooltip-left" data-container="body" title="Example (left aligned):<br>Tooltip doesn't fit the single line, and is not a sibling">Hover over me 2</span></div>
<div><span class="tooltip-large tooltip-left" title="Example (left aligned):<br>This long text we want to have in the single line">Hover over me 3</span></div>
CSS
.tooltip-inner.tooltip-large {
max-width: 300px;
}
.tooltip-inner.tooltip-left {
text-align: left;
}
Here is working demo: https://www.bootply.com/Mz48qBWXFu
Note I was not able to run this code on jsfiddle, which uses Bootstrap 4. It throws an error:
TOOLTIP: Option "template" provided type "function" but expected type "string"Apparently some additional tweaking is necessary there.
UPDATE
Everything above was an overkill in 2 places:
Instead of posting the tooltip styling classes in the class property of an element, it is better to use a data- property. That would simplify the tooltipTemplate function and remove the startsWith code shim:
tooltipTemplate = function () {
var tooltipClasses = $(this).data('tooltip-custom-classes');
return '<div class="tooltip" role="tooltip"><div class="tooltip-arrow ' + tooltipClasses +'"></div><div class="tooltip-inner ' + tooltipClasses +'"></div></div>';
}
Much more important, we don't need to modify tooltip template at all.
We should have a callback to the inserted.bs.tooltip event. That would simplify everything (thanks go to Oleg for his answer https://stackoverflow.com/a/42994192/9921853):
Bootstrap 3:
$(document).on('inserted.bs.tooltip', function(e) {
var tooltip = $(e.target).data('bs.tooltip');
tooltip.$tip.addClass($(e.target).data('tooltip-custom-class'));
});
Bootstrap 4:
$(document).on('inserted.bs.tooltip', function(e) {
var tooltip = $(e.target).data('bs.tooltip');
$(tooltip.tip).addClass($(e.target).data('tooltip-custom-class'));
});
Here are the whole examples:
for Bootstrap 3
for Bootstrap 4
try this
<i id="my-tooltip-1" class="fa fa-fire fa-lg" data-toggle="tooltip" data-placement="bottom" title="Fire Place"></i>
<style>
#my-tooltip-1 + .tooltip > .tooltip-inner {
padding: 15px;
font-size: 120%;
background-color: #FFEB6C;
color: #374D40;
/* do something */
}
#my-tooltip-1 + .tooltip > .tooltip-arrow {
background-color: #FFEB6C;
/* do something */
}
</style>
I too have been searching (far and wide) for an answer to apply different styles to selective tooltips in Bootsrap 4 and to say I was getting frustrated is an understatement.
Lots of threads simply address styling global .tooltip-inner or using scripting to accomplish this, even Bootstrap probably should have provided a simpler way.
Anyhow here's my own personal scenario & workaround.
I generally stick to the basic Bootstrap tooltip options (I assume this is working already, otherwise see update below) for various tooltips appearing on pages, but on my Navbar I have a keyboard shortcut Favicon in an anchor tag which I wanted to style. The way I accomplished this is by wrapping it in a span tag (or "data-container" as George put it [see credits]).
<link href='https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css' rel='stylesheet'/>
<link href='https://use.fontawesome.com/releases/v5.6.3/css/all.css' rel='stylesheet'/>
<script src='https://code.jquery.com/jquery-3.3.1.slim.min.js'/>
<script src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js'/>
<script src='https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js'/>
<nav>
...
<span class="tt_kb">
<a class="nav-item nav-link px-2" href="#" data-toggle="tooltip" placement="auto" data-html="true" container="body" trigger="hover" data-container=".tt_kb" data-boundary="window" title="Keyboard Shortcuts ... blah blah blah"><i class="far fa-keyboard"></i></a>
</span>
...
</nav>
<style>
.tt_kb .tooltip .tooltip-inner {
background-color: #3266FF;
text-align: left;
width: 200px;
position: relative;
right: 50px;
}
</style>
The odd thing for me is that for some reason the [position="auto"] didn't work (well) as I have the tt_kb Favicon on the top right hand side of the Navbar, half of the tooltip was disappearing outside my window, hence I added [position:relative & right:50px] in the CSS to get around this. Overall this worked reasonably well for me and I suppose with a little tweaking you could get this to work in your scenario.
Hope this help )
credits: Idea came from George's "Using a custom style for each tooltip" commnent on thread stackoverflow/questions/re-color-tooltip-in-bootstrap-4 which sadly I could not even mark as useful of comment on due to me being new without reputation (
UPDATE
For those who don't have the general Bootstrap/Popper tooltips working you may want to add the following script & general styles to your code.
<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
$('[data-toggle="tooltip"]').each(function(){
var options = {
html: true
};
if ($(this)[0].hasAttribute('data-type')) {
options['template'] =
'<div class="tooltip ' + $(this).attr('data-type') + '" role="tooltip">' +
' <div class="tooltip-arrow"></div>' +
' <div class="tooltip-inner"></div>' +
'</div>';
}
$(this).tooltip(options);
});
</script>
</style>
.tooltip.primary .tooltip-inner { background-color: #31b0d5; }
.tooltip.primary.top > .tooltip-arrow { border-top-color: #337ab7; }
.tooltip.primary.right > .tooltip-arrow { border-right-color: #337ab7; }
.tooltip.primary.bottom > .tooltip-arrow { border-bottom-color: #337ab7; }
.tooltip.primary.left > .tooltip-arrow { border-left-color: #337ab7; }
.tooltip.info .tooltip-inner { background-color: #31b0d5; }
.tooltip.info.top > .tooltip-arrow { border-top-color: #31b0d5; }
.tooltip.info.right > .tooltip-arrow { border-right-color: #31b0d5; }
.tooltip.info.bottom > .tooltip-arrow { border-bottom-color: #31b0d5; }
.tooltip.info.left > .tooltip-arrow { border-left-color: #31b0d5; }
.tooltip.success .tooltip-inner { background-color: #449d44; }
.tooltip.success.top > .tooltip-arrow { border-top-color: #449d44; }
.tooltip.success.right > .tooltip-arrow { border-right-color: #449d44; }
.tooltip.success.bottom > .tooltip-arrow { border-bottom-color: #449d44; }
.tooltip.success.left > .tooltip-arrow { border-left-color: #449d44; }
.tooltip.warning .tooltip-inner { background-color: #ec971f; }
.tooltip.warning.top > .tooltip-arrow { border-top-color: #ec971f; }
.tooltip.warning.right > .tooltip-arrow { border-right-color: #ec971f; }
.tooltip.warning.bottom > .tooltip-arrow { border-bottom-color: #ec971f; }
.tooltip.warning.left > .tooltip-arrow { border-left-color: #ec971f; }
.tooltip.danger .tooltip-inner { background-color: #d9534f; }
.tooltip.danger.top > .tooltip-arrow { border-top-color: #d9534f; }
.tooltip.danger.right > .tooltip-arrow { border-right-color: #d9534f; }
.tooltip.danger.bottom > .tooltip-arrow { border-bottom-color: #d9534f; }
.tooltip.danger.left > .tooltip-arrow { border-left-color: #d9534f; }
</style>
UPDATE
Added fully working JSFiddle Demo
NB For some reason the Navbar won't align right in the demo unless you view it zoomed at 110% or 125%!
Related
I have This simple website that i need to make it change from light theme to dark theme, the light theme works fine, but the dark theme only changes its button properly because when i click in the button to change the "body" elements should change its class from "light-theme" to "dark-theme", instead it changes to "light-theme dark-theme"
here's HTML
`
<body class="light-theme">
<h1>Task List</h1>
<p id="msg">Current tasks:</p>
<ul>
<li class="list">Add visual styles</li>
<li class="list">add light and dark themes</li>
<li>Enable switching the theme</li>
</ul>
<div>
<button class="btn">Dark</button>
</div>
<script src="app.js"></script>
<noscript>You need to enable JavaScript to view the full site</noscript>
Heres CSS
:root {
--green: #00FF00;
--white: #FFFFFF;
--black: #000000;
}
.btn {
position: absolute;
top: 20px;
left: 250px;
height: 50px;
width: 50px;
border-radius: 50%;
border: none;
color: var(--btnFontColor);
background-color: var(--btnBg);
}
.btn:focus {
outline-style: none;
}
body {
background: var(--bg);
}
ul {
font-family: helvetica;
}
li {
list-style: circle;
}
.list {
list-style: square;
}
.light-theme {
--bg: var(--green);
--fontColor: var(--black);
--btnBg: var(--black);
--btnFontColor: var(--white);
}
.dark-theme{
--bg: var(--black);
--fontColor: var(--green);
--btnBg: var(--white);
--btnFontColor: var(--black);
}
and heres JavaScript
'use strict';
const switcher = document.querySelector('.btn');
switcher.addEventListener('click', function () {
document.body.classList.toggle('dark-theme')
var className = document.body.className;
if(className == "light-theme") {
this.textContent = "Dark";
} else {
this.textContent = "Light";
}
console.log('current class name: ' + className);
});
`
I tried to change some things in css but later found that the problem might be in the javascript, but my code is exactly as the code in my course is.
when i click in the button to change the "body" elements should change its class from "light-theme" to "dark-theme", instead it changes to "light-theme dark-theme"
That's indeed true - your JS code is only toggling the class "dark-theme" and does nothing with the "light-theme" class.
So a simple fix would be to toggle both classes:
switcher.addEventListener('click', function () {
document.body.classList.toggle('dark-theme')
document.body.classList.toggle('light-theme'); // add this line
var className = document.body.className;
if(className == "light-theme") {
this.textContent = "Dark";
} else {
this.textContent = "Light";
}
console.log('current class name: ' + className);
});
But you could simplify your code because you really don't need 2 classes here. If light theme is the default, just remove the light-theme class and all its CSS rules, and apply those to body instead. The .dark-theme rules will override these when the class is set, but not otherwise.
After pressing the button, the arrow I got is
something like this :
Is there a way for me to increase the size of the arrow so that it is more visible? Thanks for any help.
function ChangetoArrows() {
var str = document.getElementById("Arrows").innerHTML;
var res = str.replace(/undefined|turn-right|turn-slight-left|turn-slight-right|turn-left/gi, function ChangetoArrows(x){
if(x=='undefined'){return x='↑';}
if(x=='turn-right'){return x='→';}
if(x=='turn-slight-right'){return x='→';}
if(x=='turn-left'){return x='←';}
if(x=='turn-slight-left'){return x='←';}
else{return x;}//must need
});
document.getElementById("Arrows").innerHTML = res;
}
.button4{
background-color: Yellow;
color: black;
padding: 5px 10px;
text-align: center;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
<button class="button4" onclick="ChangetoArrows()">ChangetoArrows</button>
HTML code renders as text so you can use font-size to adjust size.
Since it looks like you're putting these into an element with id Arrows you should be able to add this to your css:
#Arrows {
font-size: 30px;
}
→ is an example of HTML unicode. Learn more here: https://www.w3schools.com/charsets/ref_utf_arrows.asp
You can increase the font-size of button. for eg: font-size:25px and add in .button4 class.
You could add a CSS class to the element, which defines a larger font-size: document.getElementById("Arrows").classList.add('big-arrows');
Or you could use Font Awesome arrows, which will be bolder than unicode arrows.
Simply wrap it with span and give css. checkout my snippet, hopefully it can help you in some way. have a nice day
function ChangetoArrows() {
var str = document.getElementById("Arrows").innerHTML;
var res = str.replace(/undefined|turn-right|turn-slight-left|turn-slight-right|turn-left/gi, function ChangetoArrows(x){
if(x=='undefined'){return x='↑';}
if(x=='turn-right'){return x='→';}
if(x=='turn-slight-right'){return x='→';}
if(x=='turn-left'){return x='←';}
if(x=='turn-slight-left'){return x='←';}
else{return x;}//must need
});
document.getElementById("Arrows").innerHTML = '<span class="arrow">'+res+'<span>';
}
.button4{
background-color: Yellow;
color: black;
padding: 5px 10px;
text-align: center;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
.arrow{
font-size:150px;
color:red;
}
<button class="button4" onclick="ChangetoArrows()">ChangetoArrows</button>
<div id="Arrows">turn-right</div>
The others already answered the question, so I'm not going to repeat that. However, in this case I would recommend you to use Material Design - Icons:
.material-icons.md-24 { font-size: 24px; }
.material-icons.md-34 { font-size: 34px; }
.material-icons.md-44 { font-size: 44px; }
.material-icons.md-54 { font-size: 54px; }
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
<i class="material-icons md-24">arrow_back</i>
<i class="material-icons md-34">arrow_forward</i>
<i class="material-icons md-44">arrow_upward</i>
<i class="material-icons md-54">arrow_downward</i>
Just add the CSS library to your code and replace with JS like so:
return x='<i class="material-icons md-24">arrow_back</i>';
$(document).ready(function(){
$('.fa').hide();
$('.icon').click (function(){
$('.icon').addClass('active');
if($(".fa").css("display") == "none") {
$(".fa").show();
}
if $('.icon').click && $('.icon').hasCalss('active') (function(){
$(".fa").hide();
});
});
});
I want it so that when you click on a div(in this case '.icon') The div .fa shows but when I click on it again and .fa is showing it hides .fa
In the console it keeps on coming up with these 2 errors
Uncaught SyntaxError: Unexpected identifier SyntaxError: Unexpected
identifier
but I don't know whats wrong as i'm quite new to jquery and java-script.
Help would be appreciated.
Thank you :)
You need to use toogle function :
$(document).ready(function(){
$('.fa').hide();
$('.icon').click (function(){
$('.icon').addClass('active');
$(".fa").toogle();
});
});
https://www.w3schools.com/jquery/eff_toggle.asp
If it is just about switching classes on click you can use the .toggleClass()-method:
Link to toggleClass() on http://api.jquery.com.
Just use your CSS-Class to manipulate the state.
$(document).ready(function(){
const icon = $('.icon');
icon.click(function() {
$(this).toggleClass("active");
});
});
.container {
border: 1px solid grey;
padding: 0.5em;
text-align: center;
}
.icon {
opacity: 0.5;
font-size: 48px;
color: #ddd;
transition: all 300ms linear;
cursor: pointer;
}
.icon.active {
opacity: 1;
color: #bada55;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" rel="stylesheet"/>
<section class="container">
<span class="icon active">
<i class="fas fa-stroopwafel"></i>
</span>
<span class="icon">
<i class="fas fa-balance-scale"></i>
</span>
</section>
I have the code as here in this jsfiddle, I want the font awesome icon to change on button click using javascript, but it does'nt seem to work. I'm new to javascript so please forgive me if this was a dumb question.
HTML
<button id="favBtn" onclick="fav();">
<i id="favIcon" class="fa fa-star-o"></i> Favourite
</button>
Javascript
function fav() {
document.getElementById("favIcon").toggleClass('fa-star-o fa-star');
}
When using jQuery you never need to use an inline attribute eventHandler.
onclick=
Demo 1 uses jQuery .toggleClass()
Demo 2 uses JavaScript .classList.toggle()
Demo 3 uses CSS :checked pseudo-class
Update v4 to v5: Go to Start | Font Awesome. There are some class changes as well. See Demo 4.
Demo 1 -- jQuery
$('button').on('click', fav);
function fav(e) {
$(this).find('.fa').toggleClass('fa-star-o fa-star');
}
:root {
font: 400 16px/1.5 Verdana;
}
button {
display: inline-block;
font: inherit;
padding: 0px 5px;
cursor: pointer;
}
button::after {
content: ' Favorite'
}
<link href='https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css' rel='stylesheet'>
<button>
<i class="fa fa-star-o"></i>
</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Demo 2 -- Plain JavaScript
document.querySelector('button').addEventListener('click', fav);
function fav(e) {
const tgt = e.target.firstElementChild;
tgt.classList.toggle('fa-star');
tgt.classList.toggle('fa-star-o');
}
:root {
font: 400 16px/1.5 Verdana;
}
button {
display: inline-block;
font: inherit;
padding: 0px 5px;
cursor: pointer;
}
button::after {
content: ' Favorite'
}
<link href='https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css' rel='stylesheet'>
<button>
<i class="fa fa-star-o"></i>
</button>
Demo 3 -- Pure CSS
:root {
font: 400 16px/1.5 Verdana;
}
#fav {
display: none
}
#fav+label {
display: inline-block;
border: 2px outset grey;
padding: 0px 5px;
cursor: pointer;
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
}
#fav+label::after {
content: ' Favorite'
}
#fav+label>.fa-star-o {
display: inline-block
}
#fav+label>.fa-star {
display: none;
}
#fav:checked+label>.fa-star-o {
display: none;
}
#fav:checked+label>.fa-star {
display: inline-block
}
<link href='https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css' rel='stylesheet'>
<input id='fav' type='checkbox'>
<label for='fav'>
<i class="fa fa-star-o"></i>
<i class="fa fa-star"></i>
</label>
Demo 4 -- Font Awesome 5
jQuery / JavaScript / CSS
/* #1 jQuery */
$('button.jq').on('click', jQFav);
function jQFav(e) {
$(this).find('.fa-star').toggleClass('fas far');
}
/* #2 JavaScript */
document.querySelector('button.js').addEventListener('click', JSFav);
function JSFav(e) {
const tgt = e.target.firstElementChild;
tgt.classList.toggle('far');
tgt.classList.toggle('fas');
}
/* #1 JS / #2 jQ */
:root {
font: 400 16px/1.5 Verdana;
}
button {
display: inline-block;
font: inherit;
padding: 0px 5px;
cursor: pointer;
}
button::after {
content: ' Favorite'
}
/* #3 CSS */
#fav {
display: none
}
#fav+label {
display:inline-block;
border: 2px outset grey;
padding: 0px 5px;
cursor: pointer;
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
}
#fav+label::after {
content: ' Favorite'
}
#fav+label>.far {
display: inline-block;
}
#fav+label>.fas {
display: none;
}
#fav:checked+label>.far {
display: none;
}
#fav:checked+label>.fas {
display: inline-block
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" crossorigin="anonymous">
<ol>
<li><fieldset>
<legend>jQuery</legend>
<button class='jq'>
<i class='fa-star far'></i>
</button>
</fieldset></li>
<li><fieldset>
<legend>Plain JavaScript</legend>
<button class='js'>
<i class='fa-star far'></i>
</button>
</fieldset></li>
<li><fieldset>
<legend>Pure CSS</legend>
<input id='fav' type='checkbox'>
<label for='fav'>
<i class="fa-star far"></i>
<i class="fa-star fas"></i>
</label>
</fieldset></li>
</ol>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
.toggleClass() is a jQuery function and you're using it as JavaScript. Try this:
$("#favIcon").toggleClass('fa-star-o fa-star');
Difster's response is correct. Here is how you can accomplish the same thing using native JavaScript:
document.getElementById("favIcon").classList.toggle('fa-star-o');
document.getElementById("favIcon").classList.toggle('fa-star');
Additionally with what Difster said, .toggleClass is a jQuery function.
Beyond that, I wouldn't use the DOM to define bindings to functions; Using jQuery's event listener system will allow for more maintainable and understandable code:
https://jsfiddle.net/0n1n9o9n/2/
$(document).ready(function() {
$('#favBtn').on('click', function() {
$("#favIcon").toggleClass('fa-star-o fa-star');
});
});
I would split my comment into multiple remarks:
1/ As mentioned in the other comments: $("#favIcon").toggleClass('fa-star-o fa-star'); This is a mix of JS and JQuery calls.
If you want to use pure JS you would use:
document.getElementById("favIcon").classList.toggle('fa-star-o');
If you want to use JQuery you can use () As mentioned in Difster's comment:
$("#favIcon").toggleClass('fa-star-o');
2/ As mentioned already in the comments, it's better to attach an event listener.
Your Fiddle js would look like this:
document.getElementById("favBtn").addEventListener("click", fav);
function fav() {
document.getElementById("favIcon").classList.toggle('fa-star-o');
document.getElementById("favIcon").classList.toggle('fa-star');
}
And remove the "onClick" on the HTML since you would be attaching a js event listener.
Links to check:
JQuery toggleClass - js classList
Hope It Helps
$('.fa-star').click(function() {
$(this).toggleClass('fas far');
})
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
<script src="https://unpkg.com/jquery/dist/jquery.min.js"></script>
<i class="far fa-star"></i>
You can use only Javascript:
function fav() {
var icon = document.getElementById("favIcon");
if (icon.classList.contains("fa-star-o")) {
icon.classList.remove("fa-star-o");
icon.classList.add("fa-star");
} else {
icon.classList.remove("fa-star");
icon.classList.add("fa-star-o");
}
}
example
I have like link like this:
My Button
and css style:
.tree li a:hover, .tree li a:hover+ul li a {
background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}
And my question is how to change this .tree style to another one? And if i click again the style return to the beginning style?
it can be done in plain javascript as below :
var id = 'myElementId';
var myClassName = " tree";
var d;
function changeClass() {
d = document.getElementById(id);
if (d.className == ' tree') {
d.className = d.className.replace(myClassName, "");
} else {
//d=document.getElementById('myElementId');
d.className = d.className.replace(myClassName, ""); // first remove the class name if that already exists
d.className = d.className + myClassName; // adding new class name
}
}
.tree {
background: #c8e4f8;
color: #000;
border: 1px solid #94a0b4;
}
<a id="myElementId" href="#" onclick="changeClass()">My Button</a>
now in jQuery it can be achieved using toggle as below :
var id = 'myElementId';
var myClassName = " tree";
function changeClass() {
$('#' + id).toggleClass(myClassName);
}
.tree {
background: #c8e4f8;
color: #000;
border: 1px solid #94a0b4;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="myElementId" href="#" onclick="changeClass()">My Button</a>
Use classList.toggle("className") to toggle a class.
var div = document.getElementById("myDiv");
div.classList.toggle("myClassToggle");
Use this small javascript function:
function toggleClass(el, class1, class2) {
if(new RegExp("\\b"+class1+"\\b").test(el.className)) {
el.className = el.className.replace(new RegExp("\\b"+class1+"\\b",'g'),class2);
} else {
el.className = el.className.replace(new RegExp("\\b"+class2+"\\b",'g'),class1);
}
}
a {
display:block;
padding:10px;
color:white;
}
.myclass1 {
background:red;
}
.myclass2 {
background: green;
}
My Button
Edit: make sure that the classname is not in another word
A simple way to do this would be create another css class selector and assign to it your desired styles in the css file say .my-tree for example.
.my-tree {
color: red;
}
Now when your anchor is clicked you can add this css class to your tree element.
var treeEl = document.getElementById("tree");
treeEl.className = treeEl.className + " my-tree":
Similarly you can also remove this css class. You can use a variable in your code as a flag and use to add/remove the css class.
A simple way of doing this is to use the
toggleClass method of jquery which does this in a seamless manner.
Just going to throw this out there - you can do it in pure CSS:
[type=checkbox] {
display:none;
}
/* This selects the div tag immediately following the checkbox */
[type=checkbox] + div {
background:red;
cursor:pointer;
}
/* The same selector, except this is active when the checkbox is checked */
[type=checkbox]:checked + div {
background:blue;
color:#fff;
}
<label>
<input type="checkbox">
<div>Change me!</div>
</label>
This breaks a few rules for valid HTML, but if all you need is to toggle something (and not care about validation or quirksmode), this solution is pretty simple. If you do care about validation:
[type=checkbox] {
display:none;
}
[type=checkbox]:checked + label {
background:blue;
color:#fff;
}
[type=checkbox] + label {
background:red;
display:block;
}
<input id="toggler" type="checkbox">
<label for="toggler">
Change me!
</label>
Just something to chew on.
You can use jQuery
HTML:
My Button
JS:
$( "#myLink" ).click(function() {
$( "#myLink" ).toggleClass("first");
$( "#myLink" ).toggleClass("second");
});
CSS:
.first {
background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}
.second {
background: #000; color: #fff; border: 1px solid #94a0b4;
}