Change text on Hover using JQuery - javascript

I am trying to change a navigation element from 'ME' to <ME> on hover using JQuery. Here's what I'm trying:
JSBin example
However, it's permanently hiding my original text. Does anyone have an idea as to what I'm doing wrong? (I'm super new to JQuery/ JS in general)

Classical case of no js required, you could use CSS pseudo classes, specifically:
:hover
:before
:after
Example
li a:before {
content: "<";
display: none;
}
li a:after {
content: ">";
display: none;
}
li a:hover:before {
display: inline;
}
li a:hover:after {
display: inline;
}

DEMO
Try this. I have edited your code
$( function() {
var text;
$("#topnav li ").hover(
function () {
text=$(this).find("a").text();
$(this).find("a").text($(this).attr('full'));
},
function () {
$(this).find("a").text(text);
}
);
});
Hope this helps
Thank you

I agree with #Nirazul, if you can, go for a pure css solution.
If you can't, just remember that you are:
obtaining the value a of a attribute of the li
replacing the text of link inside of the selected li with its contents
reversing the operation on handlerOut
So:
$( function() {
$("#topnav li").hover(
function () {
var myLi = $(this);
myLi.attr('small', $('a', myLi).text());
$('a', myLi).text(myLi.attr('full'));
},
function () {
var myLi = $(this);
$('a',myLi).text(myLi.attr('small'));
}
);
});
Updated example.

Related

why the jquery click event is working in plunker but not in any of the browser

Hi i am making a UI in which jquery click event is used.It is working in plunker but not in any of the browser can someone please tell me why
my plunker link is plunker link
and my code for jquery is
var s="<span class='" + id + "'style='border: 1px Solid Black;position:absolute;height:25px;left:" + left1 + "px;background-color:" + color11 + ";width:" + k + "px'>" + name + "<div class='tooltip'><table id='jumble'><tbody><tr><th>Resource Type</th><th>Resource Category</th><th>Resources</th><th>Skills</th></tr> <tr><td>types</td><td>category</td><td>count</td><td>skills</td></tr></tbody></table></div></span>";
$('span').click(function(){
$(this).closest("span").find(".tooltip").toggle("slow");
});
In your html I only saw one span so why don't you use something like this:
$('span').click(function(){
$(this).find(".tooltip").toggle("slow");
});
If you have several clickabble span in you dom you can use:
$('span').each(function(){
$(this).click(function(){
$(this).find(".tooltip").toggle("slow");
});
});
You are writing $(document).ready() function twice in your scripts.That is causing the issue.
Thanks
By reading your code it's not clear if you are appending the span html element via javascript or not.
By the way, if you append the element after the "DOMContentLoaded" event (aka jQuery Document Ready) you are not able to register any event listener on it, so, you probably need to use a delegate event which is explained at this link.
Have a look on this example:
jQuery(document).ready(function($) {
var container = $('#container');
var newElement = $('<span />', {
text: "click on me"
});
window.setTimeout(function() {
container.append(newElement);
}, 2000);
var counter = 0;
container.delegate('span', 'click', function(event) {
counter += 1;
$('#counter').text(counter);
});
});
#container
{
padding: 1em .5em;
background: lightseagreen;
}
#container span
{
display: inline-block;
cursor:pointer;
padding: 1em .5em;
background: lightcoral;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter">0</div>
<div id="container"></div>
To my understanding you are adding the span control dynamically to your page. You can not use the .click() event binder for the dynamically generated control.
To make this work use the .on() as shown below
$('body').on('click','span',function(){
$(this).closest("span").find(".tooltip").toggle("slow");
});

Hide div if the ul is empty

Here is my html,
<div id="personaldetails">
<ul>
<li class="clear"></li>
</ul>
<ul>
<li class="clear"></li>
</ul>
</div>
I want to hide div personaldetails when all the ul inside in div is empty.
If the ul is having element <li class="clear"></li> then the ul is considered as to be empty.
How to do this using Jquery ?
You can try this:
$('#personaldetails').find('ul').each(function(){
var txt = $("li", this).text();
if(txt.length <= 0){
$(this).hide();
}
});
if(!$('#personaldetails').find('ul:visible').length){
$('#personaldetails').hide();
}
Updated Fiddle
And to me you should hide all ul, if no ul are visible then you can hide the #personaldetails div.
Even one of answer is already accepted, I think it can be simple as:
if($.trim($("#personaldetails").text()) == '') {
$("#personaldetails").hide();
}
:)
Take a look at that code:
function foo(){
var all_li_clear = true;
$("#personaldetails > ul > li").each(function(){
if(!$(this).hasClass("clear")){
all_li_clear = false;
break; // No need to continue now
}
});
if(all_li_clear){
$("#personaldetails").hide();
}
}
You can see a fiddle example there, just comment and discomment foo(); line.
Javascript solution:
This will only hide the div if all li have clear class
$(function() {
emptyLi = $('#personaldetails ul li').filter(function(){
/*if($(this).hasClass('clear')){
return true;
}else{
return false;
}*/
return $(this).hasClass('clear');
}).length;
if($('#personaldetails ul li').length == emptyLi){
$('#personaldetails').css('display','none');
}
});
CSS:
This will hide the li with class clear, so if you not fixed height of ul or li and don't have padding , margin given to ul,li your div personaldetails will get hidden automatically when all li element have class clear
#personaldetails ul li.clear{
display:none;
}
-UPDATED-
You can use following code if you are deciding empty class based on clear class.
if($("#personaldetails ul li:not(.clear)").length == 0) {
$("#personaldetails").hide();
}
Or if you are looking for the empty div then you can just use the shortest code given by #Samiul Amin Shanto Like:
if($.trim($("#personaldetails").text()) == '') {
$("#personaldetails").hide();
}
Explanations
Method1:
$("#personaldetails ul li:not(.clear)")
This code find all li without the clear class. Then if no such li found, just hide the div. Fiddle
Method2:
$("#personaldetails").text() this code return innerHTML text striping all html tags. So no meter what the div contain ul, li or anything else, this will return the plain text content of the div, then striping any white space we can determine if the div is empty. If your intention is to hide the empty div not hiding the div which contain empty Ul this should be your choice.
This asumes that if you have the same amount of li's with the class clear, as there are ul's, they're all empty
var $wrapper = $('#personaldetails');
if( $wrapper.find('ul').length=== $wrapper.find('li.clear').length){
$wrapper .hide();
}
Everybody's fiddling examples :)
$(function($) {
$cnt = 0;
$('.personalDetails ul li').each(function() {
if($(this).hasClass('clear')) $cnt++;
});
if($('.personalDetails ul li').length == $cnt) $('.personalDetails').hide();
});
$("ul li:empty").closest('div#personaldetails').hide();
Sample Code
#personaldetails ul li.clear{
visibility:hidden;
}

I want to center two buttons inside a div

How can I center those two buttons in JS:
// create a sort by alphabet button
var sortabc = $('Sort alphabetically').toggle(
function(){
$("#tags ul li").tsort({order:"asc"});
},
function(){
$("#tags ul li").tsort({order:"desc"});
}
);
$('#tags').append(sortabc);
// create a sort by alphabet button
var sortstrength = $('Sort by strength').toggle(
function(){
$("#tags ul li").tsort({order:"desc",attr:"class"});
},
function(){
$("#tags ul li").tsort({order:"asc",attr:"class"});
}
);
$('#tags').append(sortstrength);
At this moment I get them like this:
Button 1 Button 2
I want them in the middle of the div.
With CSS, in your style sheet:
#tags {
text-align : center;
}
With jQuery, setting that same CSS property:
$('#tags').css("text-align", "center");
Demo: http://jsfiddle.net/z77Lm/
Try using tag inside the div:
<div>
<center>
...BUTTONS
</center>
</div>

Setting CSS color with javascript onclick

Hi i am trying to make my menu link go red when i am on that page and its not working.
Html:
<li><a id="home" onclick="changeClass('home')" href="index.php">Home</a></li>
CSS:
#topMenu li{
display:inline;
margin-right:60px;
font-size:12px;
font-weight:bold;
color:#000;
text-decoration:none;
}
#topMenu li a{
color:#000;
text-decoration:none;
}
#topMenu li a:hover{
color:#666;
text-decoration:underline;
}
.topMenuon{
color:#F00
}
Javascript:
function changeClass(id)
{
var element = document.getElementById(id);
element.className = element.className + ”topMenuon”;
}
Any ideas on how i could get this to work?
You might want to do that server side, but if for some reason you cannot
and you cannot use jQuery:
function changeClass (id) {
var el = document.getElementById(id);
if (el.href == location.pathname) el.className += 'topMenuon';
};
It's simpler to Include Jquery, and do this:
$('#home').on('click',function(){
$(this).addClass('topmenuon');
});
However, it won't work like that if you are going to another page. You must detect what page you are on somehow in javascript/jquery (using something in the url, or using identifier on the page such as the section title), and then add your class while you are on that page (or,do it server side and don't call it at all if server renders directly). Can't use onclick like that if you're leaving the page anyway, new page has no way of knowing if you are doing full postback rather than ajax!
Plain js
window.onload = function(){
document.getElementById("home").onclick = function(){
this.className +=" topMenuon" ;
}
}
Edit
You are probably going to a new page on the click of the link. Hence the above code would not change the class of the link since you are now on a new page.
You may need to add the class to the link using php(i assume you are using it).
Apply as
var element = document.getElementById('home');
element.setAttribute("className", newClass);
function changeClass()
{
var element = document.getElementById('home');
element.className += 'topMenuon';
}
<li><a id="home" onclick="changeClass();" href="#">Home</a></li>
use jquery - this in the <head>...
<script src="yourPath/jquery_1.8.0_min.js" type="text/javascript"></script>
then...
$(document).ready(function(){
$("#home").addClass('topMenuon');
}
that'll do it...
S

How to reference this CSS in Javascript?

i have the following CSS for a mouse hover event. Im not sure how to refer to the #tabs ul li a:hover from within the Javascript?
#tabs ul li a:hover
{
color: #000;
font-weight:bold;
background-color: #0ff;
}
and i wish to swap the background color line for this Javascript code:
<script type="text/javascript">
hex=255;
function fadetext(){
if(hex>0) {
hex-=11;
document.getElementById("#tabs ul li a:hover").style.color="rgb("+hex+","+hex+","+hex+")";
setTimeout("fadetext()",50);
}
else
hex=255;
}
</script>
This:
document.getElementById("#tabs ul li a:hover")
isn't valid syntax, you only need to specify the id there:
document.getElementById("tabs")
You can change the style of an element on hover something like this:
var elem = document.getElementById("id");
elem.onmouseover = function(){
// your code
};
Let's suppose you have assigned the id myid to your link, you can do the stuff for that like this:
var elem = document.getElementById("myid");
elem.onmouseover = function(){
elem.style.backgroundColor = 'color value';
elem.style.color = 'color value';
};
Update:
Since in your code you are using loadit(this) in onclick event, you don't need to use document.getElementById because element is already referenced with this keyword, also you may want to use the onmouseover event instead of click event if you want to something to happen when element is hovered like:
<li><a href="tab-frame-workexperience.html" target="mainFrame" onmouseover="loadit(this)" >Work experience</a></li>
and then your function should look like this:
function loadit(elem)
{
elem.style.color = 'color value';
}
and/or you can create the two functions for two events if you want.
Note also that you can use jQuery to do it easily and in unobstrusive fashion with hover method:
$(function(){
$('#tabs ul li a').hover(function(){
$(this).css('color', '#ff0000'); // this fires when mouse enters element
}, function(){
$(this).css('color', '#000'); // this fires when mouse leaves element
}
);
});
Do you mean like this? This didn't work...
#tabs ul li a:hover
{
color: #000;
font-weight:bold;
<script type="text/javascript">
hex=255;
var elem = document.getElementById("tabs");
elem.onmousehover = function fadetext(){
if(hex>0) {
hex-=11;
elem.style.color="rgb("+hex+","+hex+","+hex+")";
setTimeout("fadetext()",50);
}
else
hex=255;
}
</script>
}
One solution is to edit your stylesheet instead of changing the style of every element, this can be done with a simple one-liner:
document.styleSheets[0].insertRule("#tabs ul li a:hover{rgb(255, 255, 255);}", 0);
Where the second argument specifies that the rule should be inserted first in the stylesheet.
For IE this is done with the addRule function instead:
document.styleSheets[0].addRule("#tabs ul li a:hover", "rgb(255, 255, 255)");
Update:
In your case, it would mean replacing this row:
document.getElementById("#tabs ul li a:hover").style.color="rgb("+hex+","+hex+","+hex+")";
with
var ss = document.styleSheets[0]; //gets the first external stylesheet in your document
if(ss.insertRule) //checks browser compatibility
ss.insertRule("#tabs ul li a:hover{rgb("+ hex + ", " + hex + ", " + hex + ");}", 0);
else
ss.addRule("#tabs ul li a:hover", "rgb("+ hex + ", " + hex + ", " + hex + ")");

Categories

Resources