Jquery What have I done wrong? - javascript

$(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>

Related

Why does my jquery onclick function toggle on and off, if I run initialization more than once?

I have a website with a few icons/buttons that trigger a simple menu when you click them. However, I need to be able to load more data, with more of these buttons, and since the existing buttons are initialized with a function, using jquery onclick, i figured I would just re-run that function whenever the number of buttons are changed.
I expected the existing onclick functions to be simply overwritten, with the same content as before. Even though it is not optimal code, I expected it to work fast, and simple.
But then I discovered that running the onclick initializing function simply toggles the working elements. In other words the newly generated elements now works, but the existing ones does not. Calling the function a third time toggles them all back, meaning the original works, but not the new. This baffles me.
I made a JSFiddle, showing what I mean:
To see the different scenarios of original state, added button and toggled, and thirdly toggled back, just comment out lines in the document ready function in javascript
$(document).ready(function() {
initContextMenuButtons(); //initializes cog-icon buttons
addThirdButton(); //adds a third button, and calls init again, toggling all
initContextMenuButtons(); //toggles back
});
HTML:
<div id="wrapper">
<div class="relative-wrapper">
<i class="fa fa-2x fa-cog context-menu-button"></i>
<div class="tooltip-wrapper">
<div class="tooltip">
<div class="edit-button"><i class="fa fa-fw fa-pencil-square-o" aria-hidden="true"></i>Edit button</div>
<div class="delete-button"><i class="fa fa-fw fa-trash-o" aria-hidden="true"></i> Delete button</div>
<div class="close-button"><i class="fa fa-fh fa-times" aria-hidden="true"></i></div>
<div class="tooltip-arrow-wrapper"><b class="tooltip-arrow"></b></div>
</div>
</div>
</div>
<div class="relative-wrapper">
<i class="fa fa-2x fa-cog context-menu-button"></i>
<div class="tooltip-wrapper">
<div class="tooltip">
<div class="edit-button"><i class="fa fa-fw fa-pencil-square-o" aria-hidden="true"></i>Edit button</div>
<div class="delete-button"><i class="fa fa-fw fa-trash-o" aria-hidden="true"></i> Delete button</div>
<div class="close-button"><i class="fa fa-fh fa-times" aria-hidden="true"></i></div>
<div class="tooltip-arrow-wrapper"><b class="tooltip-arrow"></b></div>
</div>
</div>
</div>
</div>
Javascript:
$(document).ready(function() {
initContextMenuButtons();
addThirdButton();
initContextMenuButtons();
});
function initContextMenuButtons() {
$('.context-menu-button').click(function() {
var this_wrapper = $(this).siblings(".tooltip-wrapper").toggle();
$(".tooltip-wrapper").not(this_wrapper).hide();
});
$('.tooltip .close-button').click(function() {
$(this).closest(".tooltip-wrapper").hide();
});
}
function addThirdButton() {
var html = ' <div class="relative-wrapper">' +
'<i class="fa fa-2x fa-cog context-menu-button"></i>' +
'<div class="tooltip-wrapper">' +
'<div class="tooltip">' +
'<div class="edit-button"><i class="fa fa-fw fa-pencil-square-o" aria-hidden="true"></i>Edit button</div>' +
'<div class="delete-button"><i class="fa fa-fw fa-trash-o" aria-hidden="true"></i> Delete button</div>' +
'<div class="close-button"><i class="fa fa-fh fa-times" aria-hidden="true"></i></div>' +
'<div class="tooltip-arrow-wrapper"><b class="tooltip-arrow"></b></div>' +
'</div>' +
'</div>' +
'</div>'
$('#wrapper').append(html);
initContextMenuButtons();
}
CSS:
.relative-wrapper {
position: relative;
}
.tooltip .close-button {
position: absolute;
top: 0px;
right: 1px;
color: #999;
}
.tooltip .close-button:hover {
color: #555;
}
.tooltip-wrapper {
display: none;
position: absolute;
top: -6px;
left: 38px;
z-index: 1;
}
.tooltip {
transition: none 0s ease 0s;
width: 200px;
height: 55px;
background-color: rgb(246, 246, 246);
border: 1px solid #ccc;
border-radius: 4px;
position: relative;
box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 4px 0px;
}
.tooltip .edit-button {
position: absolute;
top: 7px;
left: 8px;
width: 185px;
cursor: pointer;
}
.milestone-tooltip .edit-button:hover {
background-color: #ddd;
}
.tooltip .delete-button {
position: absolute;
top: 28px;
left: 6px;
width: 185px;
cursor: pointer;
}
.tooltip .delete-button:hover {
background-color: #ddd;
}
.tooltip-arrow-wrapper {
height: 24.8px;
width: 16px;
display: block;
transition: none 0s ease 0s;
left: -14px;
top: 11px;
position: absolute;
}
.tooltip-arrow {
height: 10px;
width: 10px;
border-top: 1px solid rgb(187, 187, 187);
border-left: 1px solid rgb(187, 187, 187);
background-color: rgb(246, 246, 246);
transform: translate(8px, 4px) rotate(-45deg);
position: absolute;
}
.context-menu-button {
cursor: pointer;
}
Existing event handlers don't get overwritten. The new event handlers simply stack on top of them. One click now fires the event multiple times.
I'd highly recomment using Event Delegation for the following reasons:
Dynamically created elements will just work. No need to attach new events.
With your current method, hypothetically, if you have 10 elements, that's 10 event handlers. Event delegation allows you to have just 1, whether you have 1 element or 1,000.
It's nearly identical to your existing code. You're simply attaching the event to the document instead of the element itself.
function initContextMenuButtons() {
$(document).on('click', '.context-menu-button', function() {
var this_wrapper = $(this).siblings(".tooltip-wrapper").toggle();
$(".tooltip-wrapper").not(this_wrapper).hide();
});
$(document).on('click', '.tooltip .close-button', function() {
$(this).closest(".tooltip-wrapper").hide();
});
}
initContextMenuButtons() should now only be fired once throughout the life of the page, so be sure to remove the call from your addThirdButton() method, as well as the second call from your $(document).ready( ... ).
Your event listeners add up. To make multiple initializations work, you can remove existing ones first.
$('.context-menu-button').off().click(function() {
// ...
$('.tooltip .close-button').off().click(function() {
In general, you can also use namespaces to prevent accidentally removing other event listeners.
$('.context-menu-button').off('.init').on('click.init', function() {
// ...
$('.tooltip .close-button').off('.init').on('click.init', function() {
SOLUTION:
Remove initContextMenuButtons() function and its references. Add the following code.
$('#wrapper').on('click', '.context-menu-button', function () {
var this_wrapper = $(this).siblings(".tooltip-wrapper").toggle();
$(".tooltip-wrapper").not(this_wrapper).hide();
});
$('#wrapper').on('click', '.tooltip .close-button', function() {
$(this).closest(".tooltip-wrapper").hide();
});

Enlarging Arrow Size in Javascript

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>';

Toggle font awesome class on button click

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

Bootstrap Tooltips with different styles

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%!

js fails to incorporate into php page

I have the following js code:
<style>
<!--
body
{
font-family: "century schoolbook", serif;
font-size: 20px;
}
.hidden
{
display: none;
color: #000;
background: #FFFFFF;
}
.unhide
{
display: block;
color: #000;
}
a.unhide
{
text-decoration: none;
}
a.unhide:hover
{
text-decoration: underline;
}
.unhide:hover
{
background: #FFE5B4;
padding: 3px 8px;
display: table-row;
transition: background .25s ease-in-out;
-moz-transition: background .25s ease-in-out;
-webkit-transition: background .25s ease-in-out;
}
-->
</style>
<script type="text/javascript">
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className = (item.className == 'hidden') ? 'unhide' : 'hidden';
}
}
</script>
...
<div class="conBoxcities">
<class id="info">
<a href="javascript:unhide('cityname');" class="unhide">
This is really a js link with a city name. Clicking brings down information about
that city.
</a>
</class>
<class id="info">
<div id="cityname" class="hidden">
This is where the content of the above link appears. It is just an info blurb,
basically.
This js script works here. On the other page it does not. I believe I messed up
somewhere in my classes...please help
</div>
</class>
</div>
The above code works perfectly well on a "bare" php page
When I incorporate it into my main page, the js links no longer function. I believe i may have a mistake in my arrangement (admittedly, classes and ids still confuse me).
This is the page where the link appears, but does not work.
Please help...
The problem is that in your "live" page you have redefined the function unhide with this code:
function unhide(divID) {
var item = document.getElementsByClassName(divID)[0];
console.log(item);
console.log(item.className == divID + ' hide');
if (item) {
item.className = (item.className == divID + ' hide') ? divID + ' unhide' : divID + ' hide';
}
}
If you remove, our comment out that code, everything works as expected.

Categories