Change color of element onMouseOver using javascript - javascript

I'm writing javascript which will change the color of an element when the mouse hovers over it. I know perfectly how to do this using jQuery, but this time around I have to do it using either pure JS or Prototype.
Why doesn't this work:
<div id="boundary1"></div>
document.getElementById("boundary1").onmouseover(function() {
alert("test");
})
firebug returns:
TypeError: document.getElementById(...).onmouseover is not a function

Your syntax is wrong, you may be thinking a little too 'jQuery', try this:
var boundary = document.getElementById('boundary');
var mouseOverFunction = function () {
// this.style.color = '#000'; // your colour change
};
boundary.onmouseover = mouseOverFunction;
I've separated the logic to make the development and logic clearer, it makes your functions reusable too.

The Prototype way to do this would be this:
$('elementId').observe('mouseenter', function(evt){
this.setStyle('background-color: yellow');
}).observe('mouseleave', function(evt){
this.setStyle('background-color: inherit');
});
But as others have already pointed out, the real way to do this is with CSS. The only reason I could imagine needing to do it in JS is if you have to support IE <= 8, which doesn't like to do the :hover pseudo-class on anything except the A tag.

Try:
document.getElementById("boundary1").onmouseover = function() {
alert("test");
}
More Info.

Try this code
<td onMouseOver="this.bgColor='#00CC00'" onMouseOut="this.bgColor='#009900'" bgColor=#009900>
Click Here</TD>

You can do it using CSS
<style>
.changecolour:hover
{
background-color:yellow;
}
</style>
Now for the text you want to change color
<span class ="changecolour">Color changes when mouse comes here.</span>
Reference : http://www.w3schools.com/cssref/sel_hover.asp

Related

Make javascript work on any link

I would like for an effect to happen (a certain <div id="posts"> to translate left) when clicking on any link of my page. I was wondering if there was a way to do this with javascript. The only thing I thought about was the function but to add the attribute onclick="myFunction" to all of my links would be so long..
Maybe there is a pre-made js function that works on any link?
I also thought about using CSS a:active but I don't think that would be the best idea.
Thanks for the replies! :)
You can use jQuery to look for clicks on the <a> element, and call a function from there:
$('a').click(function() {
// code to translate div left
});
You can use jQuery to make things work like this:-
$('a').click(myfunction);
function myFunction() {
//do click event stuff here :)
}
If you need a pure JavaScript alternative, I'm not sure if this will work but here's something you can try:
var a = document.getElementsByTagName("p");
for(var i=0; i<p.length; i++){
p[i].onclick = function(){
myFunction();
}
}
function myFunction() {
//do click event stuff here :)
}
For a better understanding, you can refer to http://jsbin.com/onaci/
I'm sorry if I misunderstood you. If so, please correct me.
Thanks

Hide an HTML <img ...> with javascript

I am trying to make a simple game about sliding ice-blocks. However, I tested this JSFiddle and I want to "hide" the image/button on the line alert('Game starts!');. I tried startButton.style = "visibility: hidden;"; but it didn't work...
I only need to resolve this problem, I know how to code the game itself :)
Adding this after the alert seems to work.
this.style.display = 'none';
updated Fiddle
try document.getElementById("startButton").style.display="none"
try
document.getElementById("startButton").style.visibility = 'hidden';
HTMLElement.style reference (MDN)
You can also use jQuery UI, which has a "hide" method. You can then simply say
$('.startButton').hide()
You can even apply different effects.
However, this will set the visibility to none, removing the object from the DOM. If you don't care about that, it's fine, but it should be borne in mind.
startButton.onclick = function()
{
startButton.style.visibility="hidden";
/* OR
startButton.style.display="none";
*/
alert('Game starts!');
}

.hover not working when used with .html

I am trying to do a simple image rollover with jQuery, but this code is not working:
HTML:
<div class="secondcircle" id="circleone">
<p>
<img src="/../ex/img/group1.png">
</p>
</div>
JS:
$("#circleone").hover(
function () {
$(this).html("<p><img src=\"/../ex/img/group2.png\"></p>");
},
function () {
$(this).html("<p><img src=\"/../ex/img/group1.png\"></p>");
}
);
The mouse enter event fires just fine, but none happens when the mouse leaves.
Moreover, the code works fine with simpler actions - the example in the jQuery docs of appending a span then removing it works just fine.
Why would the html not be working? I've been stuck on this for ages.
Update: Nearly every answer/comment suggests just replacing the image source, and while this works perfectly (thanks!) sometimes I do need to change the HTML (such as to change text). This was just one example. Sorry, I should have better specified that in the question.
Instead of replacing your entire HTML is is a better idea to just change the source of the image.
$("#circleone").hover(function () {
$(this).find('img').attr("src","/../ex/img/group2.png\");
},
function () {
$(this).find('img').attr("src","/../ex/img/group1.png\");
}
);
It works if you adjust it so it just replaces the img, like this:
http://jsfiddle.net/7etUU/
I think the main issue is your div being a block element that spans 100% of the width, then the contents get replaced on hover which removes the content, so it flashes.
Why not do this with CSS?
#circleone {
background-image:url('FirstImageURL');
}
circleone:hover{
background-image:url('SecondImageURL');
}
Totally stole this from this question.
I think your div is taking 100% width. Try adding a "float:left" CSS property. Like this...
.secondcircle{
float : left;
}
I noticed something weird when testing this. His original method does not work until I added a border around the parent div, then it works just fine.
Anyone know why that might be?
jsFiddle
/*UNCOMMENT ME AND I WILL WORK
#circleone
{
border: 1px solid #000;
}*/
You do not need to replace the whole HTML with hover event. If your goal is to change the image on hover, use the attr method instead http://api.jquery.com/attr/:
HTML
<div class="secondcircle" id="circleone">
<p>
<img id="img1" src="http://softwarebyrob.wpengine.netdna-cdn.com/images/football.jpg" />
</p>
</div>
jQuery
$("#circleone").hover(
function () {
$("#img1").attr({ 'src': 'http://softwarebyrob.wpengine.netdna-cdn.com/images/programming.jpg', 'alt':'MyAlt1' });
},
function () {
$("#img1").attr({ 'src': 'http://softwarebyrob.wpengine.netdna-cdn.com/images/football.jpg', 'alt':'MyAlt2' });
}
);
Working JsFiddle here: http://jsfiddle.net/TBMxm/1/
Also, this is better from performance and best practice point of view.
Update1
jQuery Code if you want to use HTML method:
var originalContent = $('#circleone p').html();
$("#circleone").hover(
function () {
$('#circleone p').html('<img src="http://softwarebyrob.wpengine.netdna-cdn.com/images/programming.jpg"/>');
},
function () {
$('#circleone p').html(originalContent);
}
);
Working sample using HTML: http://jsfiddle.net/TBMxm/3/

IE not taking my onClick, any suggestions?

I have a pretty simple function that seems to work fine in Chrome, Firefox, and Safari, but in IE it's breaking. I'm actually trying to load this as a Windows 8 Web App, but from what I've read, that uses a more forgiving version of IE10 to output.
Say I have a <div> (or an <a> with an href...I've tried this as well) like so:
<div onClick="showSection('myTemplate.html');"></div>
This is my function:
function showSection(loca) {
$("#optionView").show();
$("#bookMenu").hide();
$("#optionView").load('settings/'+loca);
$("#settingsButton").attr("onClick","showSettingsMain();");
}
Why wouldn't this work specifically in IE?
A better option, especially since you are using jQuery, is to not use inline event handlers.
Instead, use this HTML:
<div id="main_div"></div>
And use this Javascript:
$(document).ready(function () {
$("#main_div").on("click", function () {
showSection("myTemplate.html");
});
});
This may not solve your problem with IE10, but it's considered better practice...and should work consistently with all browsers.
A few other suggestions:
Instead of using .attr to set the onclick attribute of #settingsButton, you might as well use on again:
$("#settingsButton").on("click", function () {
showSettingsMain();
});
Although I'm not exactly sure if that would have any effect on what the problem is.
Nonetheless, here's an explanation on the difference between attr and prop - .prop() vs .attr()
Also, if you need to specify exactly what URL to use, even on a per-<div> basis, you could use a data-* attribute. Say this is your HTML:
<div class="trigger-div" data-target-url="myTemplate.html"></div>
<div class="trigger-div" data-target-url="myTemplate2.html"></div>
Then you could use:
$(document).ready(function () {
$(".trigger-div").on("click", function () {
var $this = $(this);
var target_url = $this.attr("data-target-url"); // or $this.data("target-url")
showSection(target_url);
});
});
Clicking the first div will use "myTemplate.html", while clicking the second will use "myTemplate2.html".
This way, your data is embedded in your HTML, but your Javascript is unobtrusive.
You are using jQuery wrong, here:
First, bind the event to the div, you'll need to add a class or id for that:
<div id="myEvent"></div>
Then, bind the event:
$('#myEvent').on('click', showSection( 'myTemplate.html') );
And your function:
function showSection(loca) {
$("#optionView").show();
$("#bookMenu").hide();
$("#optionView").load('settings/'+loca);
}
Try that way.

jQuery Tipsy won't work with jQuery.each() and live:true

Note: This question was marked as solved once, but it figured out that upgrading to the latest jQuery was fixed only one issue. Please see the updated question below for the remaining issue.
Hi all,
I have just run into a weird issue with jQuery.Tipsy.
Here's a simplified demo fiddle: http://jsfiddle.net/6nWtx/7/
As you can see, the lastly added a.tipsy2 element does not get tipsyfied. The .tipsy2 elements are being tipsyfied within a jQuery.each() function and at this point I have the problem. Without the each() it works. Unfortunately, I need .each() to iterate through the elements to do some other stuff before I call tipsy().
Any suggestion?
Here's the source code of Tipsy: https://github.com/jaz303/tipsy/blob/master/src/javascripts/jquery.tipsy.js
IMHO the problem is using the combination of jQuery.each() and Tipsy option live:true
Update:
The other stuff I want to do before calling .tipsy() is checking for some optional configuration.
For example: Help"
In this example I will add the following option to Tipsy: delayIn:1000 If there is no delayed class associated to the element this parameter will be delayIn:0.
Using the same logic, I want to specify the following classes as well: show-top, show-left, show-right, show-bottom for the Tipsy option called gravity.
Example: Help"
The full code:
$(".tipsyfy").each(function () {
var a = "s",
b = 0;
if ($(this).hasClass("show-left")) a = "w";
else if ($(this).hasClass("show-down")) a = "n";
else if ($(this).hasClass("show-right")) a = "e";
if ($(this).hasClass("delayed") && $(this).attr("data-delayIn") != null) b = $(this).attr("data-delayIn");
$(this).tipsy({
gravity: a,
fade: true,
live: true,
delayIn: b
})
})
And here is a full jsFiddle demo with all the stuffs I want to do: http://jsfiddle.net/xmLBG/1/
If you use jQuery 1.7.1 instead of 1.6.4 it will work. Maybe that live feature is relying on something buggy with the older versions, or some not-yet-implemented feature.
Update: from what I understood, you want the tipsy plugin to be called to every element with the .tipsyfy class, present now or added in the future. You don't want to (or can't) call it explicitly before insertion. You're trying to accomplish that using the live option of the plugin. Is that right?
If that's the case I can offer a workaround. I tried to use on (since jQuery's live is deprecated) to bind some code to the load event, but it didn't work, so I bound it to mouseenter and checked whether or not the plugin was already built for that element. If not, it builds it and re-triggers the event.
$(document).on("mouseenter", ".tipsyfy", function(e) {
if ( !$(this).data("tipsy") ) {
e.preventDefault();
var a = "s",
b = 0;
if ($(this).hasClass("show-left")) a = "e";
else if ($(this).hasClass("show-down")) a = "n";
else if ($(this).hasClass("show-right")) a = "w";
if ($(this).hasClass("delayed") && $(this).attr("data-delayIn") != null) b = $(this).attr("data-delayIn");
$(this).tipsy({
gravity: a,
fade: true,
live: true,
delayIn: b
}).trigger("mouseenter");
return false;
}
});
Live example at jsFiddle.
For a small optimization, if the sole purpose of the .tispsyfy class is to instruct the plugin creation, and you don't need it afterwards, you can remove it prior to re-triggering the mouseenter. This way the checking code won't be called over and over again:
$(this).tipsy({...}).removeClass("tipsyfy").trigger("mouseenter");
As far as I can see, you don't need to iterate the nodelist. It looks like tipsy does that for you (see this jsfiddle, where in the first list every element gets its own tooltip (1,2,3).
KooiInc is right,
<a class="tipsy1" href="#" title="Tipsy">TipsyLink</a>
<a class="tipsy1" href="#" title="Tipsy">TipsyLink</a>
<a class="tipsy1" href="#" title="Tipsy">TipsyLink</a>
<br />
<div id="container"></div>
<input id="add" type="button" value="ok">
And
$(".tipsy1").tipsy({live:true,fade:true});
$(".tipsy2").tipsy({live:true});
$("#add").click(function() {
$("#container").append('<a class="tipsy2" href="#" title="Tipsy">TipsyLink</a>');
});
That will work fine
My guess is that Tipsy are uses some kind of direct mapping to the result, not using the live (in 1.6) or on in newer versions of jQuery.
So when your trying to apply the plugin to the links with the class tipsy2 it cant find any (cause your adding it to the DOM at a later stage in your code). The easiest fix to this is just to run the tipsy function at a later stage, perhaps on document.ready.
// this works
$(".tipsy1").tipsy({live:true,fade:true});
// add new tipsy element (ok)
$(document.body).append('<a class="tipsy1" href="#" title="TipsyAjax">AjaxTipsy1</a><br/>');
// add new tipsy element (not ok)
$(document.body).append('<a class="tipsy2" href="#" title="Tipsy">TipsyLink</a>');
$(document).ready(function () {
$(".tipsy2").each(function(){
// I'm doing some other logic here before I call .tipsy()
$(this).tipsy({live:true,fade:true});
})
});
(http://jsfiddle.net/8dg6S/7/)
Can't you do this instead? It is what you are asking.
$(".tipsy1,.tipsy2").tipsy({live:true,fade:true});
$(".tipsy2").each(function() {
//do your stuff
});

Categories

Resources