Changing the background image when clicking on the div? - javascript

I am creating a table with div's that already have a background image in them. The classes are "sw", "sl", "so", "sa", "sn", and "su". I made that you could click on the div's and to the right will show the information for that div.
However, I tried adding a hover element to these div's, which work when I do not add the onclick function. With the onclick function, there is no hover that changes the div into a different background image. The background image stays the same when I click on a certain div.
How can you make the background image change when you click on the div?
Here is my HTML code:
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td><div class="sw" onclick="show(0)"></div></td>
<td><div class="sl" onclick="show(1)"></div></td>
<td id="info" rowspan="3" style="width:325px;"></td>
</tr>
<tr>
<td><div class="so" onclick="show(2)"></div></td>
<td><div class="sa" onclick="show(3)"></div></td>
</tr>
<tr>
<td><div class="sn" onclick="show(4)"></div></td>
<td><div class="su" onclick="show(5)"></div></td>
</tr>
</table>
And here is my JavaScript code:
function show(num) {
var outputInfo = "";
if(num == 0) {
outputInfo += 'INFO HERE';
}
else if(num == 1) {
outputInfo += 'INFO HERE';
}
...
document.getElementById("info").innerHTML = outputInfo;
}
Oh, and by the way, my background images are used on the CSS portion and all of the classes above share the same image but they were assigned different positions.
Is there a way to show the images as separate backgrounds if another approach to clicking on a div?

Instead of using onclick, maybe try using something Tomm did. I probably encourage you to create a class for all of these id elements. Since you had a shared background image for the original background before the function is clicked, I added background-position. Here is what I did for the script by making a function that I put in the onload of the body (first portion is for backgrounds when clicked, second portion is for original background and will only show for those that are not clicked):
function onloadPage() {
// first portion
$('#sw').click(function() {
$(this).css("background-position", "0 0");
document.getElementById("info").innerHTML = 'INFO HERE';
});
$('#sl').click(function() {
$(this).css("background-position", "0 0");
document.getElementById("info").innerHTML = 'INFO HERE';
});
...
// second portion
$('.classname').on('click', function(e) {
if(!$(e.target).closest('#sw').length) { $('#sw').css("background-position", '0 0'); }
if(!$(e.target).closest('#sl').length) { $('#sl').css("background-position", '0 0'); }
...
}
And then the HTML:
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td><div class="classname" id="sw" style="background-position:0 0;"></div></td>
<td><div class="classname" id="sl"></div></td>
<td id="classinfo" rowspan="3" style="width:325px;"></td>
</tr>
</table>
Obviously you will have to adjust your background-positions to the way you need it to look.

Well, your code should looks like:
document.getElementById("info").style.backgroundImage = "url('image.png')";
here I am assuming that info is the id of the div which you want to change background.

This snippet should do. I've linked a couple of random images so you can test it.
By clicking on the div, the info is displayed on the right and that div's background gets updated. By passing the 'this' keyword as argument of the show method you can avoid logics that depend on the div's id.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<style>
.sw{
background-image: url("https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png");
}
.sl{
background-image: url("https://mdn.mozillademos.org/files/7693/catfront.png");
}
</style>
<script>
function show(num, t) {
var outputInfo = "";
if(num == 0) {
outputInfo += 'This is the information about the image now displayed in div0';
var newUrl='url("http://www.librosweb.es/website/css/images/logo.gif")';
t.style.backgroundImage= newUrl;
}
else if(num == 1) {
outputInfo += 'This is the information about the image now displayed in div1' ;
var newUrl='url("http://www.librosweb.es/website/css/images/logo.gif")';
t.style.backgroundImage= newUrl;
}
document.getElementById("info").innerHTML = outputInfo;
}
</script>
<table width="100%" cellpadding="0" cellspacing="0" >
<tr>
<td style="border: 1px solid red"><div class="sw" onclick="show(0, this)"></div></td>
<td style="border: 1px solid red"><div class="sl" onclick="show(1, this)"></div></td>
<td style="border: 1px solid red" id="info" rowspan="3" style="width:325px;"></td>
</tr>
</table>
</body>
</html>

You can make a simple onclick function in javascript/jQuery ( I use this code with jQuery 1.7.1 ) like the following:
$('#changeMe').on('click', function() {
$('#changeMe').css('background-image', 'url(urlhere)');
})
Where #changeMe is the div id
$('#changeMe').on('click', function() {
$('#changeMe').css('background-image', 'url(http://firefoxzeneize.altervista.org/FirefoxLogo.png)');
})
div{
width : 512px;
height : 512px;
background-image : url("https://www.notebookcheck.net/fileadmin/Notebooks/News/_nc3/20170911_Google_Chrome_logo_vector_download.png");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="changeMe"></div>

Related

My JS scrollTo function does not scroll the page

My goal is to have a clickable button/link to scroll to a certain position in a page. I have referenced from this answer by Michael Whinfrey, the code works perfectly on fiddle but not on mine.
This may be a bit messy but I have multiple GridViews in a table, and some td has div and some don't. Also in the code behind I have the following code in Page_load.
Page.MaintainScrollPositionOnPostBack = false;
Below is my aspx page simplified.
<html>
<head>
<script type="text/javascript">
function scrollTo(name) {
ScrollToResolver(document.getElementById(name));
}
function ScrollToResolver(elem) {
var jump = parseInt(elem.getBoundingClientRect().top * .2);
document.body.scrollTop += jump;
document.documentElement.scrollTop += jump;
if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
elem.lastjump = Math.abs(jump);
setTimeout(function () { ScrollToResolver(elem); }, "100");
} else {
elem.lastjump = null;
}
}
</script>
</head>
<body>
.......some input/textbox......
<button onclick="scrollTo('divDesignation')">TEST</button>
<div>
<table>
<tr>
<td>
<asp:GridView id="gv1" .....>
......the whole table has 6~7 rows of GridView data that is not displaying here.....
<tr>
<td>
<div id="divDesignation" runat="server" style="max-height:600px; overflow-y:auto;">
<asp:GridView id="gvDesignation" ......
</div>
</td>
</tr>
</body>
</html>
I am trying to scroll to the divDesignation when click the button but it simply will not.
Any help is appreciated.

Javascript Function that changes Text Color, Hyperlink Color, and Image

Hi,
I need help with a class assignment. We were given an HTML file for a pretend business, "Castaway Vacations LLC". The first step in the assignment is to create a javascript function that changes the Text Color, Hyperlink Color, and Image when a particular link is clicked. So when the "Romantic" link is clicked, for example, the text that reads "Select Mood" will change to red, along with all other text on the page (including the other hyperlinks). Clicking this link will also change the image. One thing that's tricky about the file that our teacher sent is that there isn't a matching CSS file - I created one myself that contains the class colors, but besides that, all the other styles are inline, which I'm not used to. Here is the JSfiddle link to my code:
UPDATE!
I've gotten the code down for changing text color and image, but the hyperlink colors still aren't changing. You can see my attempt at changing them with the function named colorLinks in the updated javascript. Unfortunately, not only does this function not work, it's also causing the previous (good) functions to not work as well. Thanks for your help.
http://jsfiddle.net/HappyHands31/twkm12r2/1/
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Castaway Vacations, LLC</title>
</head>
<body leftmargin=0 rightmargin=0 bgcolor=#ffcc99
text=#993300 link=#993300 vlink=#996633>
<br>
<table width=100% border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=95% align="right" bgcolor=#ffffff>
<img src="castaway_logo.jpg">
<br>
<font face=arial>Vacations, LLC</font></td>
<td bgcolor=#ffffff> </td>
</tr>
</table>
<br><br>
<div align="center">
<table width=600>
<tr>
<td width=300 valign="top">
<font face=arial size=3><b><i>Select Mood...</i></b></font><br><br>
<font face=arial>
<a id="one" href="#">Romantic</a><br><br>
<a id="two" href="#">Adventure</a><br><br>
<a id="three" href="#">Relaxation</a><br><br>
<a id="four" href="#">Family</a><br><br><br>
<br>
Request A Brochure...
</font>
</td>
<td align="center"><img id="original.jpg" src="orig_main.jpg">
<br> <i>Your Vacation Awaits!
</tr>
</center>
<script src="castaway.js"></script>
</body>
</html>
</DOCTYPE>
Javascript:
document.getElementById('one').addEventListener
('click', change_color);
document.getElementById('two').addEventListener
('click', change_color2);
document.getElementById('three').addEventListener
('click', change_color3);
document.getElementById('four').addEventListener
('click', change_color4);
function change_color(){
document.body.style.color = "red";
document.getElementById("original.jpg").src = "rom_main.jpg";
}
function change_color2(){
document.body.style.color = "blue";
document.getElementById("original.jpg").src = "adv_main.jpg";
}
function change_color3(){
document.body.style.color = "green";
document.getElementById("original.jpg").src = "rel_main.jpg";
}
function change_color4(){
document.body.style.color = "orange";
document.getElementById("original.jpg").src = "fam_main.jgp";
}
colorLinks ("#00FF00");
function colorLinks (hex)
var links = document.getElementsByTagName("a");
for(var i=0;i<links.length;i++)
{
if(links[i].href)
{
links[i].style.color = "red";
}
}
Thank you!
ok, for starters to change color of something you just need to do something like this
function change_color(){
document.body.style.color = "red"; // this will change the color of the text to RED
document.getElementById("image_to_change").src = "something.jpg"; // change img src
}
to use the function just add the call to the function where you want it, for example
<a onClick="change_color();" href="#">Romantic</a><br><br>
well, its already accepted answer, but just wanted to complete it, to change the img src of, first you need to add an id for that img, for example
<td align="center"><img id="image_to_change"src="orig_main.jpg"><br><i>Your Vacation Awaits!
after you added the id, you can see how i added this line to the "change_color" function
document.getElementById("image_to_change").src = "***SOURCE_TO_YOUR_IMAGE***";
* Working Code *
OK, here is the working fiddle http://jsfiddle.net/8ntdbek3/1/
i changed a few things to make it work, first, you need to understand that when you give an "ID" to something, in this case to the img (you gave the id "rom_main.jpg") the ID is what you need to use to call that element, so when you are using
document.getElementById("orig_main.jpg").src = "rom_main.jpg";
it should go
document.getElementById("rom_main.jpg").src = "rom_main.jpg";
since you gave it the id "rom_main.jpg" in this line, and the id "orig_main.jpg" does not exist!
<td align="center"><img id=**"rom_main.jpg**" src="orig_main.jpg"><br><i>Your Vacation Awaits!
also its important to note that you can put ANY id that you want, so repeating the name of the jpg file its something that i would not recommend, since it leads to confusion.
I changed the ID to something more readable and thats it. if you still need help comment below and i'll do my best to help you.
* EDIT to change color *
ok, finally i added a few lines of code to change the color of EVERY element in your page, for each onclick i adde these lines:
var list = document.getElementsByTagName("a");
for (i = 0; i < list.length; i++) {
list[i].style.color = "red";
}
as you can see, i get in a list every element with the tag "a", then every element i turn it into "red" (or the color you want).
here is the working fiddle http://jsfiddle.net/8ntdbek3/3/
regards.

colResizable row display:none; and the custom anchors relating to the row to have a display:none;

I am a bit stuck and was wondering if anyone could please help me? I am developing a website that has colResizable JQuery plugin incorporated into it. The plugin is all good and brilliant -its just that I need to have a button that once selected makes the middle row of the colResizable table have a display of none with the custom anchors (relating only to that table row) also having a display of none. And once the button is selected, it is replaced with a button that has 'show', then once that is selected the middle row of the colResizable table appears and the custom anchors of that row also appear. Here is the code that I have so far:
<!DOCTYPE html>
<html lang="en">
<head>
<title>colResizable demo</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<script src="js/jquery.js"></script>
<script src="js/colResizable-1.5.min.js"></script>
<script type="text/javascript">
$(function(){
var onTableCreated = function(){
$("#updatePanelSample").colResizable({
liveDrag:true,
gripInnerHtml:"<div class='grip'></div>",
draggingClass:"dragging",
postbackSafe:true,
fixed:false,
partialRefresh:true,
});
}
var fakePostback = function(){
$("#updatePanel").html('<img src="img/loading.gif"/>');
setTimeout(function(){
$("#updatePanel").html('<table id="updatePanelSample" width="500" border="0" cellpadding="0" cellspacing="0"> <tbody><tr> <th>header</th><th>header</th><th>header</th> </tr> <tr> <td class="left">cell</td><td>cell</td><td class="right">cell</td> </tr> <tr> <td class="left">cell</td><td>cell</td><td class="right">cell</td> </tr> <tr> <td class="left bottom">cell</td><td class="bottom">cell</td><td class="bottom right">cell</td> </tr> </tbody></table>');
onPostbackOver();
}, 700);
};
var onPostbackOver = function(){
onTableCreated();
};
$("#postback").click(fakePostback);
onTableCreated();
});
</script>
<script type="text/javascript">
function hide_cells(){
document.getElementById("get_cells").style.display = "none";
document.getElementById("get_cells2").style.display = "none";
document.getElementById("get_cells3").style.display = "none";
document.getElementById("get_cells4").style.display = "none";
document.getElementById("change_to_show").innerHTML = "<button onClick='show_cells()' >Show</button >";
}
function show_cells(){
document.getElementById("get_cells").style.display = "inline";
document.getElementById("get_cells2").style.display = "inline";
document.getElementById("get_cells3").style.display = "inline";
document.getElementById("get_cells4").style.display = "inline";
document.getElementById("change_to_show").innerHTML = "<button onClick='hide_cells()' >Hide</button >";
}
</script>
</head>
<body>
<div class="center" >
<br/><br/>
<div id="change_to_show"><button onClick="hide_cells()" >Hide</button ></div>
<div id="updatePanel">
<table id="updatePanelSample" width="500" border="0" cellpadding="0" cellspacing="0">
<tr>
<th>header</th><th id="get_cells">header2</th><th>header3</th>
</tr>
<tr>
<td class="left">cell</td><td id="get_cells2">cell</td><td class="right">cell</td>
</tr>
<tr>
<td class="left">cell</td><td id="get_cells3">cell</td><td class="right">cell</td>
</tr>
<tr>
<td class="left bottom">cell</td><td id="get_cells4" class="bottom">cell</td><td class="bottom right">cell</td>
</tr>
</table>
</div>
<br/>
<br/><br/>
</div>
</body>
</html>
Here is the link to the colResizable website: http://www.bacubacu.com/colresizable/
Thanks - any help is highly appreciated!
Updates - I have included some additional information below in order to illustrate what I mean more clearly:
Here is the table and the button that I am working with:
Here is what I mean by the custom anchor:
Here is what happens when I click the 'hide' button that has the 'hide_cell()' function incorporated into it via an onClick:
Notice that even though the the middle column ('header2') disappeared, the custom anchor relating to that column remains, and the other anchor is not in the correct position.
I was wondering if anyone could please help with this problem I am facing? Thanks :) Here's the link to the colResizable plugin site:http://www.bacubacu.com/colresizable/
Cells are not inline displayed. You must to change to table-cell:
document.getElementById("get_cells4").style.display = "table-cell";
There are this values for display in tables:
table > applied to <table> tag
table-row > applied to <tr> tag
table-cell > applied to <td> tag
Learn more:
http://www.w3schools.com/cssref/pr_class_display.asp
Good luck!
I think I figured it out - I needed to find the child [1] of the JCLRgrip. Then change it via the JavaScript to have a display of none, as illustrated below:
<script type="text/javascript">
function hide_cells(){
document.getElementById("get_cells").style.display = "none";
document.getElementById("get_cells2").style.display = "none";
document.getElementById("get_cells3").style.display = "none";
document.getElementById("get_cells4").style.display = "none";
document.getElementById("change_to_show").innerHTML = "<button onClick='show_cells()' >Show</button >";
document.getElementsByClassName("JCLRgrip")[1].style.display = "none";
document.getElementsByClassName("JCLRgrip")[2].style.display = "none";
}
function show_cells(){
document.getElementById("get_cells").style.display = "table-cell";
document.getElementById("get_cells2").style.display = "table-cell";
document.getElementById("get_cells3").style.display = "table-cell";
document.getElementById("get_cells4").style.display = "table-cell";
document.getElementById("change_to_show").innerHTML = "<button onClick='hide_cells()' >Hide</button >";
}
</script>
before any DOM manipulation you have to call colresizable with the param "disable" set to true.
disable: [type: boolean] [default: false] [version: 1.0]
When set to true it aims to remove all previously added enhancements such as events and additional DOM elements assigned by this plugin to a single or collection of tables. It is required to disable a previously colResized table prior its removal from the document object tree using JavaScript, and also before any DOM manipulations to an already colResized table such as adding columns, rows, etc.
so your code will be something like this
var onHideColumn = function(){
$("#updatePanelSample").colResizable({disable:true}); //disable colresizable
hide_cells(); //remove columns, or whatever
$("#updatePanelSample").colResizable(); //enable it again
}
There is a sample included in the version released for colResizable 1.6, you can download it from github or from the official website

Change tr background color when img inside td is clicked

well i am filling a table with php with values from DB
what i was trying to but unsuccessful didnt is to change the tr background color when image is clicked
here is what i tried to do
<script>
function changeColor(tr)
{
var tableRow = document.getElementById(tr);
tableRow.style.backgroundColor='red';
}
</script>
<html>
<table>
<tr id='tr<?php echo $personID;?>'>
<td>
<?php echo $personName;?>
</td>
<td>
<?php echo $personLastName;?>
</td>
<td>
<img src= "/*an image*/" onmouseover="" style="cursor: pointer;" onclick="changeColor('tr<?php echo $personID;?>')" >
</td>
</tr>
</table>
</html>
obiously this is just for one case but when i get elements from DB this table is pretty long
any ideas?
THANKS IN ADVANCE
one more thing
my table already has an css design where
td
{
background: #EDEDED;
}
tr:hover
{
background: #d0dafd;
}
this is maybe why when doing onclick="this.parentNode.parentNode.style.background='gray'"
is not working how can i fix this?
You could simply use parentNode : DEMO
<img src="http://dummyimage.com/50x50"
onmouseover="this.parentNode.parentNode.style.background='gray'"
onmouseout="this.parentNode.parentNode.style.background=''"
/>
img->parentNode=td -> parentNode=tr
jQuery code
//code for clicks
$('td img').click(function() {
$(this).closest('table').children('tr').removeClass('highlight');
$(this).closest('tr').addClass('highlight');
});
//code for hovering
$('tr').hover(function() {
//if the tr has the highlight class do nothing, otherwise add hover style
if(!$(this).hasClass('highlight')) {
$(this).addClass('hoverStyle');
}
}, function() {
//if the tr has hover style remove it when hover ends
if($(this).hasClass('hoverStyle')) {
$(this).removeClass('hoverStyle');
}
});
Then just make a CSS class to define the highlight style.

Adding a Skip Button to FastForward a .fadeIn / .fadeOut?

Just to clarify, when you load my site I have a bit of text that fades in (quote), and then fades out. Afterwards a new bit of text (my brand name) fades in.
Since I want people to have enough time to read the first text (the quote) the fade in and fade out are a bit long, however I don't want people to get impatient after visiting the site for the 5th time and having to wait every time.
Therefore I was thinking of a "skip-like" button or text (IE: SKIP) so that they can fastforward to where the brand name fades in.
Any help would be appreciated!!! Here's an example of what I currently have!!
http://jsfiddle.net/K6SpB/
HTML
<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>
<center>
<div id="mytext" align="center">
<table width="100%" height="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td valign="middle" align="center">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td height="200">
<center>
<font size="4px" id="quote" color="black">THIS IS A QUOTE.</font>
<br>
<font size="12px" id="brandname" color="black">BRAND NAME.</font>
</center>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</center>
JAVASCRIPT
$(document).ready(function() {
$('#quote').hide().delay(1000).fadeIn(5000).delay(3000).fadeOut(2000);
$('#brandname').hide().delay(11500).fadeIn(2000);
});​
CSS
<style type="text/css">
#quote, #brandname {
position:relative;
display: none;
float:center;
}
#mytext {
}
</style>​
You probably want jQuery .stop() (http://api.jquery.com/stop/)
So, if you add a Skip link:
Skip
The code would look like this:
$('#skip').click(function(e) {
e.preventDefault();
$('#quote, #brandname').stop(true, true);
});
The first "true" tells jQuery to remove any pending animations from the animation queue, the second "true" tells it to skip straight to the end of the animation.

Categories