Change color by mouse over - javascript

I'ld like to change the "imgTag.style.border='5px solid #FF00FF'" to black when the mouse is over an image.
This is my JavaScript:
javascript:for(i=0;i<document.getElementsByTagName('img').length;i++)
{
var imgTag=document.getElementsByTagName('img')[i];
imgTag.style.border='5px solid #FF00FF';
imgTag.title='';
imgTag.onclick=function()
{
return !window.open('http://www.example.com/#/'+this.src);
}
}
void(0)
How can it be done?
Thanks
Frank

You need to bind handlers to the mouseover and mouseout events to change the image's border color:
var imgs = document.getElementsByTagName('img');
for(var i = 0; i < imgs.length; ++i) {
imgs[i].onmouseover = function() {
this.style.borderColor = '#000';
};
imgs[i].onmouseout = function() {
this.style.borderColor = '#f0f';
};
}
For example: http://jsfiddle.net/bNk4Y/

Not sure what's wrong with the code you have, but if i understand your question correctly, this should do it:
HTML:
<img src="" >
<img src="">
...
JS:
var imgs = document.getElementsByTagName("img");
for(i=0;i<imgs.length;i++)
{
imgs[i].onmouseover = function() {this.style.border="1px red solid";};
}
Note, however, that this can easily be achieved with CSS as well, which is a better practice - in case users have JS disabled, etc
img:hover {
border: 1px red solid;
}

Related

Javascript/ I am stuck with changing back to the original background

I am learning JavaScript and am now doing a homework assignment.
I need to find how to remve a background image from an element after the mouse leaves the element.
I wrote the function code, Dogimgleave(), and it does not update the HTML.
Here is the code, please help me...
<img class=size src = "Images/Dog.jpg" alt="Dog!" onmouseover="Dogimgon()" onmouseleave="Dogimgleave()">
function Dogimgon(){
document.getElementById("centertext").style.backgroundImage="url('Images/Dog.jpg')";
}
function Dogimgleave() {
document.getElementById("centertext").style.backgroundColor="#65F0B6";
}
You're leaving the background image set as an image, so you won't see the background colour. You can clear the image like this...
function Dogimgleave() {
var ct = document.getElementById("centertext");
ct.style.backgroundImage = ""; // this removes the background image
ct.style.backgroundColor="#65F0B6";
}
If you set the backogrund-image and background-color simultaneously one will cover the other one. You should have only one of them set at any time:
var elem = document.getElementById("centertext");
function Dogimgon(){
elem.style.backgroundImage = "url('Images/Dog.jpg')";
elem.style.backgroundColor = "";
}
function Dogimgleave() {
elem.style.backgroundImage = "";
elem.style.backgroundColor = "#65F0B6";
}
This can be of course simplified to setting just the background property:
var elem = document.getElementById("centertext");
function Dogimgon(){
elem.style.background = "url('Images/Dog.jpg')";
}
function Dogimgleave() {
elem.style.background = "#65F0B6";
}
Or alternatively you may have color always set (it would be visible through transparent parts of the image however) and alter only the image:
var elem = document.getElementById("centertext");
elem.style.backgroundColor = "#65F0B6";
function Dogimgon(){
elem.style.backgroundImage = "url('Images/Dog.jpg')";
}
function Dogimgleave() {
elem.style.backgroundImage = "";
}
By the way, unless you task is to do that exactly in JavaScript, you may easily achieave the same result with pure CSS:
#centertext {
background: #65f0B6;
}
#centertext:hover {
background: url('/Images/Dog.jpg');
}

element.style.display is not what rendered in the browser

Probably a duplicate question but can not find the answer.
element.style.display is not what rendered in the browser.
Instead of returning the actual value (ie. block or inline etc), it returns empty. Tested in Chrome 56.0.2924.87 (64-bit).
How do I get the actual rendered value?
function displayStyle(aEvent) {
aEvent.target.textContent=aEvent.target.style.display;
}
window.onload = function() {
var top_array = document.getElementsByClassName("top");
for(var i = 0; i < top_array.length; i++)
{
top_array[i].addEventListener("click", displayStyle, false);
}
}
.top{
background-color:#FFF8DC;
}
<div class="top">top (click it and it will disappear because its style.display is empty)</div>
CSS styles are not available to JavaScript unless they have been formerly set in JavaScript or they have been hardcoded as inline styles.
Use getComputedStyle() instead:
function displayStyle(aEvent) {
var target = aEvent.target;
target.textContent = window.getComputedStyle(target).getPropertyValue('display');
}
window.onload = function() {
var top_array = document.getElementsByClassName("top");
for (var i = 0; i < top_array.length; i++) {
top_array[i].addEventListener("click", displayStyle, false);
}
}
.top {
background-color: #FFF8DC;
}
<div class="top">top (click it and it will now show "block" since we're getting its computed style.)</div>
Works if you set it directly in style attribute:
function displayStyle(aEvent) {
aEvent.target.textContent=aEvent.target.style.display;
}
window.onload = function() {
var top_array = document.getElementsByClassName("top");
for(var i = 0; i < top_array.length; i++)
{
top_array[i].addEventListener("click", displayStyle, false);
}
}
.top{
background-color:#FFF8DC;
}
<div class="top" style="display: block;">top (click it and it will disappear because its style.display is empty)</div>
Obs.: setting it on CSS also doesn't work.
I still don't know why, anyway.
Now I know, thanks to Rick Hitchcock's answer.

.append image src as text to a div

so I'm trying to append image src to a div when you click on it...so far I've written it like this and it doesn't seem to work, no error reports, no idea what's going on. The image is of a class .card (there's 15 of them), and I want to append to the div only if the border is gray, you click once to select the card (changing the border) and then click again to paste the selected card onto the div...the div is called .picks. I just want to display the image src as text on my page. thanks for the help
$(".card").click(function() {
console.log("click");
if($(this).css('border')==="4px solid gray") {
var cardname = $(this).attr('src');
$(".picks").append(cardname);
if(pick<15) {
pick++;
}
else {
booster++;
pick=1;
}
}
else {
$(this).css('border', '4px solid gray');
}
});
The problem is that you rely on result of css("border") while it's not what you expect: e.g. Chrome will retrieve border styles as "4px solid rgb(128, 128, 128)".
Instead set CSS class selected and check if the card has this class or not:
$(".card").click(function () {
if ($(this).hasClass('selected')) {
var cardname = $(this).attr('src');
$(".picks").append(cardname);
if (pick < 15) {
pick++;
} else {
booster++;
pick = 1;
}
} else {
$(this).addClass('selected');
}
});
Demo: http://jsfiddle.net/1o7tgs5j/13/
In general as the rule of thumb, avoid using $.fn.css method for styling, not only this is very obtrusive but also error prone approach. In most cases usage of addClass/removeClass brings much more flexibility.
You should be using
if($(this).css('border')==="4px solid rgb(128, 128, 128)")
{
....
}
But i will suggest you to do it this way...
$(".card").click(function () {
console.log("click");
if ($(this).hasClass("clicked")) {
var cardname = $(this).attr('src');
$(".picks").append(cardname);
if (pick < 15) {
pick++;
} else {
booster++;
pick = 1;
}
} else {
$(this).css('border', '4px solid gray').addClass("clicked");
}
});
Working Fiddle

Fade in boxes 1 after the other with jQuery

Im trying to make a 'blanket' of divs containing child divs 150px high and 150px wide.
I want each child div to fade in 1 after the other after after a millisecond or so, opacity changing from 0, to 1.
I cant seem to figure out how this works, or how id do it though?
http://jsfiddle.net/CCawh/
JS
$(function(){
var figure = [];
w = 1500;
h = 450;
for(i = 0, i < 30, i++){
$('div').append(figure[].clone()).fadeIn();
}
});
Here is a working solution.
The problems in your code
in for(i = 0, i < 30, i++), you should use ';', not ',' . Use developer tools in your browser to catch such typos
In your code $('div').append(figure[].clone()).fadeIn(); , The fadeIn applies to $('div') as append() returns the calling object itself. You must replace it with $('<figure></figure>').appendTo('div').fadeIn('slow'); and to fadeIn items one by one you could set a timeout with incrementing delays
Add display: none; style to the figure to keep it hidden initially
Here is the full code.
$(function(){
for(i = 0; i < 30; i++){
setTimeout(function(){$('<figure></figure>').appendTo('div').fadeIn('slow');}, i*200);
}
});
Here is a fiddle to see it working http://jsfiddle.net/CCawh/12/
Try using greensock TweenLite http://www.greensock.com/get-started-js/.
It has staggerTo/staggerFrom action that does exactly what you are asking. TweenLite in conjunction with jQuery makes animation very easy.
This would be a possible solution (DEMO).
Use an immediate function and call it again n times in the fadeIn callback.
$(function(){
var figure = $('figure');
var counter = 0;
(function nextFade() {
counter++;
figure.clone().appendTo('div').hide().fadeIn(500, function() {
if(counter < 30) nextFade();
});
})();
});
You can use the following implementation as an example. Using setTimeout() will do the trick.
I've updated your jsfiddle here: http://jsfiddle.net/CCawh/5/
HTML:
<div class="container">
<div class="box"></div>
</div>
CSS:
.box {
display: none;
float: left;
margin: 10px;
width: 150px;
height: 150px;
background-color: #000;
}
JS:
$(function() {
var box = $('.box');
var delay = 100;
for (i = 0; i < 30; i++) {
setTimeout(function() {
var new_box = box.clone();
$('.container').append(new_box);
new_box.fadeIn();
}, delay);
delay += 500; // Delay the next box by an extra 500ms
}
});
Note that in order for the element to actually fade in, it must be hidden in the first place, i.e. display: none; or .hide()
Here's perhaps a more robust solution without counters:
http://jsfiddle.net/CCawh/6/
for(var i = 0; i < 30; i++){
$('div').append($('<figure>figure</figure>'));
}
(function fade(figure, duration) {
if (figure)
figure.fadeIn(duration, function() { fade(figure.next(), duration); });
})($('figure').first(), 400);
By the way, clauses in for loops are separated using semicolons, not commas.

How to select the next div that does not have a certain CSS class

<div id="button">
Click me
</div>
<div id=item1> //loads with a dashed border
</div>
<div id=item2> //loads with a solid border
</div>
<div id=item3> //loads with a solid border
</div>
Script part:
var eventNext = document.getElementById("button");
eventNext.addEventListener("click", move, false);
function move()
{
}
What would I put in the move function to get the next div item that does not have a dashed border, and make it dashed, and current item's border to solid? (if there is a next item)?
var eventNext = document.getElementById("button");
eventNext.addEventListener("click", move, false);
function move() {
if( eventNext ) {
if( eventNext.id !== 'button' ) {
eventNext.className = 'solidBorder';
}
eventNext = eventNext.nextElementSibling;
if( eventNext ) {
eventNext.className = 'dashBorder';
}
}
}
.dashBorder {
border: 2px dashed blue;
}
.solidBorder{
border: 2px solid blue;
}
or with jquery
var eventNext = $("#button").bind("click", move);
function move() {
if( eventNext.length ) {
if( eventNext.attr('id') !== 'button' ) {
eventNext.attr( 'class', 'solidBorder' );
}
eventNext = eventNext.next();
if( eventNext.length ) {
eventNext.attr( 'class', 'dashBorder' );
}
}
}
if you need to support browsers that dont support nextElementSibling, use this functoin instead.
function next( elem ) {
while( (elem = elem.nextSibling) && (elem.nodeType !== 1) );
return elem;
}
Here's one way with jQuery, if using this library happens to be an option for you:
First, give each div which can become dashed, a "marker class"
<div id="item1" class="itemWhichCanBeDashed">
//loads with a dashed border
</div>
<div id="item2" class="itemWhichCanBeDashed">
//loads with a solid border
</div>
<div id="item3" class="itemWhichCanBeDashed">
//loads with a solid border
</div>
Then create a dashed border style:
<style type="text/css">
.dashed { border-style: dashed; }
</style>
Then, to dash the next div that's not already dashed:
$("div.itemWhichCanBeDashed:not(.dashed):first").addClass("dashed");
This selects all divs with the class itemWhichCanBeDashed, but does not have the dashed class attached, then takes the first one, then adds the class dashed
If you want the first div to already be dashed, then just render it with the dashed class.
I'm not sure exactly what the requirement of making the current div solid is, but it should be a simple extension of this.
EDIT
To host jQuery in your project, you can link to it from Google:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
If your user has recently visited a site that was linking to the same file, it'll likely be cached. If not, it's only about a 92K download.
This would be easier if you used a js framework like jquery. It's as simple as adding a reference to your head like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
Using jquery, the code would be
var lastChanged;
$(document).ready(function() {
lastChanged = $('#item1');
$('#button').click(function() {
$(lastChanged).css("border", "1px solid #000");
$(lastChanged).next().css("border", "1px dashed #000");
lastChanged = $(lastChanged).next();
});
});
Here it is on jsfiddle - http://jsfiddle.net/JKYue/
see if this help to get you started
<button onclick="nextItem()">Click me</button>
var nextItem = (function() {
var arr_item, arr_len, intIdx, currentItemInt;
arr_item = ["item1", "item2", "item3"];
arr_len = arr_item.length;
intIdx = -1;
currentItemInt = "";
return function(){
for (var j= 0; j < arr_len; j++) {
var elm = document.getElementById(arr_item[j]);
var os = (elm.currentStyle) ? elm.currentStyle["borderStyle"] : window.getComputedStyle(elm,"").getPropertyValue('border-top-style');
if(os == "dashed"){
intIdx = j;
//alert(j)
currentItemInt = arr_item[j + 1];
}
}
// alert(arr_item[intIdx])
if(intIdx < arr_item.length-1){
document.getElementById(arr_item[intIdx]).style.border = "white dashed";
document.getElementById(currentItemInt).style.border = "black dashed";
}
}
}());

Categories