trying to understand different $(this) in jquery - javascript

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
<style type="text/css">
#gallery
{
width: 960px;
margin: 0 auto;
}
.galleryitem
{
width: 300px;
height: 300px;
float: left;
font-family: Lucida Sans Unicode, Arial;
font-style: italic;
font-size: 13px;
border: 5px solid black;
margin: 3px;
}
.galleryitem img
{
width: 300px;
}
.galleryitem p
{
text-indent: 15px;
}
#galleryhoverp
{
margin-top: -55px;
background-color: black;
opacity: 0.5;
-moz-opacity: 0.5;
filter: alpha(opacity=50);
height: 40px;
color: white;
padding-top: 10px;
}
#singleimagedisplay
{
width: 800px;
}
#singleimagedisplay img
{
width: 800px;
}
#singleimagedisplay a
{
float: right;
color: white;
}
</style>
</head>
<body>
<div id="gallery">
<div class="galleryitem">
<img src="computer1.png" alt="A beautiful Sunset over a field" /><p>
A beautiful Sunset over a field</p>
</div>
<div class="galleryitem">
<img src="computer2.png" alt="Some penguins on the beach" /><p>
Some penguins on the beach</p>
</div>
<div class="galleryitem">
<img src="computer3.png" alt="The sun trying to break through the clouds" /><p>
The sun trying to break through the clouds</p>
</div>
<div class="galleryitem">
<img src="computer.png" alt="Palm tress on a sunny day" /><p>
Palm tress on a sunny day</p>
</div>
<div class="galleryitem">
<img src="computer4.png" alt="The sun bursting through the tall grass" /><p>
The sun bursting through the tall grass</p>
</div>
</div>
</body>
</html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$('p').hide();
var galleryItems = $('.galleryitem');
galleryItems.css('height', '200px');
var images = $('.galleryitem').find('img');
galleryItems.hover(
function () {
$(this).children('p').show().attr('id', 'galleryhoverp');
},
function () {
$(this).children('p').hide().attr('id', '');
}
)
images.click(function () {
$(this).parent().attr('id', 'singleimagedisplay').css('height', $(this).height()).siblings().hide();
})
</script>
Above code is from here: http://www.1stwebdesigner.com/tutorials/jquery-beginners-4/
Question:
For this line: $(this).parent().attr('id', 'singleimagedisplay').css('height', $(this).height()).siblings().hide();
1.I know the first $(this) means the img that clicked, but what does sencond $(this) mean?
2.when I clicked one img on the frontend, I can see see the img get enlarged, and it shows style="height: 533px; in firebug, but how come it is 533px? in css script, there is no such definition as height: 533px.

The second $(this) also means the same as the first one.
What is happening here is, you are getting the parent elemet of the clicked img then set the id to singleimagedisplay then set its height to the heigth of the img that was clicked(This gets the rendered hight of the image) then hides all the sibling elements of the images parent

Related

Positioning an image on top of text

How can I position an image on top text. Like in the image given
Here is a basic example using flex. I put a border on the div so you can see exactly what the flex does. Also, for an example like this where you want the image to be directly over text, you have to lookout for default margins/padding. For example, the <p> element has a default margin which I set to 0.
.row {
display: flex;
flex-direction: column;
border: solid 1px black;
width: 200px;
height: 80px;
padding: 20px;
background-color: #1e3f5a;
}
p {
margin: 0; /* removes default p margin */
text-align: center;
font-size: 30px;
color: white;
}
img {
align-self: flex-end;
margin-right: 1.5rem; /* optional */
}
<div class="row">
<img src="https://dummyimage.com/55x25/ed7014/fff&text=Trending">
<p>Dex Activity</p>
</div>
You can also use the position css property for this, you can wrap these two tags with a div and use the css flex methods.
CSS Flex Example:
<div style="display:flex; flex-direction:column"><img src="IMG_URL" alt="..." style="align-self:flex-end"><p>Dex Activity<p/></div>
There is more than one technique.
Here's one, borrowed from w3schools:
<!DOCTYPE html>
<html>
<head>
<style>
.container {
position: relative;
}
.topright {
position: absolute;
top: 8px;
right: 16px;
font-size: 18px;
}
img {
width: 100%;
height: auto;
opacity: 0.3;
}
</style>
</head>
<body>
<h2>Image Text</h2>
<p>Add some text to an image in the top right corner:</p>
<div class="container">
<img src="img_5terre_wide.jpg" alt="Cinque Terre" width="1000" height="300">
<div class="topright">Top Right</div>
</div>
</body>
</html>

change caption color depending on image behind it

I'm working on a portfolio site that is a full browser size container where the image is swapped when moving the cursor from left to right. I achieved this with a jquery script called swinger.js.
I had some trouble adding captions to this but with some help from here last night I got it to work using the alt attribute. The problem is now that I want to have some of the captions in white and others in black (depending on the image behind it) and I would like the same to happen to the site title.
I added a class inside the img src tag that specifies which should be which. class=“swinger_img_white” for a white caption, class=“swinger_img_black” when it needs to be black
But I can't get it to work.
My coding experience goes be a week or two, I got this far by luck, help and dedication to trying code from other websites.
Any help would be much appreciated!
*note: with caption I just mean some text that goes with the image (explaining it) by whatever way is possible.
Does not have to be built like captions as used in webdesign, just has to work.
Here is what I have right now in a simplified version:
$.fn.swinger = function () {
return this.each(function () {
var $container = $(this);
$container.css({
"position": "relative"
});
var $images = $container.find("img");
$images.css({
});
var $middleImage = $($images[Math.floor($images.length / 2)]);
$middleImage.css({
"z-index": "2",
"position": "relative"
});
var columnsCount = $images.length;
$images.each((i, img) => {
var left = `${100 / columnsCount * i}%`;
var width = `${100 / columnsCount}%`;
var $column = $(`<span style="z-index:999;position:absolute;top:0;bottom:0;left:${left};width:${width}"></span>`);
$(img).after($column);
$column.hover(() => {
$images.css({
"z-index": "1",
"position": "absolute"
});
$(img).css({
"z-index": "2",
"position": "relative"
});
// this was added last night for the captions
$(".caption").text($(img).attr("alt"));
});
})
});
}
*{
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
body {
}
.left-holder {
text-align: left;
float: left;
margin-right: 55px;
width: 250px; }
div.swinger-container {
text-align: center; /* ensures the image is always in the h-middle */
overflow: hidden;
width: 100vw;
height: calc(100vh);
}
div.swinger-container img {
object-fit: cover;
-o-object-position: center center;
object-position: center center;
width: 100%;
height: 100% !important;
}
header {
width: 100%;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
position: absolute;
top: 0;
left: 0;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
padding: 10px 10px;
-webkit-box-sizing: border-box;
box-sizing: border-box;
margin-top: -2px;
text-align: center;
z-index: 100;
-webkit-transition: all .2s;
transition: all .2s; }
header.header-about {
color: white !important;
background-color: white; }
header h1, header h2, header .about {
font-size: 1em;
font-weight: 400;
display: block;
line-height: 1.2em;
margin-bottom: 0;
padding-bottom: 0; }
header h1 {
text-align: left; }
header a {
text-decoration: none;
color: white;
line-height: 1; }
header .about {
text-align: left;
padding-bottom: 2px; }
.left-holder{
color:white
}
.caption {
text-align: right;
float: right;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="Style.css">
<title>website title</title>
<script src="./jquery-3.6.0.min.js"></script>
</head>
<body>
<header>
<div class="left-holder">
<h1>my name</h1>
<h2>what I do</h2>
</div>
<div class="caption">
</div>
</header>
<div class="slides">
<div class="swinger-container">
<img src="https://images.unsplash.com/photo-1447703693928-9cd89c8d3ac5?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1951&q=80" class=“swinger_img_white” alt="Caption 1"/>
<img src="https://images.unsplash.com/photo-1502239608882-93b729c6af43?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80" class=“swinger_img_white” alt="Caption 2"/>
<img src="https://images.unsplash.com/photo-1516557070061-c3d1653fa646?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80" class=“swinger_img_white” alt="Caption 3"/>
<img src="https://images.unsplash.com/photo-1468657988500-aca2be09f4c6?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1950&q=80" class=“swinger_img_white” alt="Caption 4"/>
<img src="https://images.unsplash.com/photo-1488554378835-f7acf46e6c98?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1951&q=80" class=“swinger_img_white” alt="Caption 5"/>
<img src="https://images.unsplash.com/photo-1491895200222-0fc4a4c35e18?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1567&q=80" class=“swinger_img_black” alt="Caption 6"/>
<img src="https://images.unsplash.com/photo-1517816743773-6e0fd518b4a6?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80" class=“swinger_img_black” alt="Caption 7"/>
<img src="https://images.unsplash.com/photo-1548685913-fe6678babe8d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1923&q=80" class=“swinger_img_black” alt="Caption 8"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(init);
function init()
{
$(".swinger-container").swinger();
}
</script>
<script src="swinger.js"></script>
</body>
</html>
I will be good if you keep some information about condition in a data attributes, like that:
<img src="https://..." data-color="white" alt="Caption 1"/>
<img src="https://..." data-color="black" alt="Caption 2"/>
Then you can change color of your caption with .css method which you will pass value from data-color attribute, like that:
$(".caption")
.text($(img).attr("alt"))
.css('color', $(img).data('color'));

How do I change the background of a button when clicked?

Okay, okay. I know many people have asked this question on Stack Overflow, but the solutions don't work for me. So my problem is simple: how do I make the female-av-button and male-av-button have a background URL of female-avatar & male-avatar respectively? Here's my code:
body{
margin: 0;
padding: 0;
box-sizing: border-box;
background-color: black;
}
.avatars{
justify-content: center;
margin-left: 15%;
display: flex;
}
.choose-a-user-text{
font-family: 'Luckiest Guy';
font-size: 400%;
justify-content: center;
}
.choose-a-username{
margin-left: 25%;
}
.user-input{
margin-left: 29%;
}
.user-input:focus{
outline: none;
}
.female-av-button{
background: none;
border: none;
padding: 1px;
}
.female-av-button:focus{
}
.male-av-button{
background: none;
border: none;
padding: 1px;
}
.female-av{
background: url('../img/female-avatar-silhouette.png') no-repeat;
width: 500px;
height: 700px;
}
.female-av:hover{
background: url('../img/female-avatar.png') no-repeat;
width: 500px;
height: 700px;
}
.male-av{
background: url("../img/male-avatar-silhouette.png") no-repeat;
width: 500px;
height: 700px;
}
.male-av:hover{
background: url("../img/male-avatar.png") no-repeat;
width: 500px;
height: 700px;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Choose Your Character</title>
<link rel="stylesheet" href="css/avatar-page.css">
<link href="https://fonts.googleapis.com/css2?family=Luckiest+Guy&display=swap" rel="stylesheet">
</head>
<body>
<div class="choose-a-username">
<h2 class="choose-a-user-text" style="color: #018D94;">CHOOSE A USERNAME</h2>
<input class="user-input" type="text" name="" value="" placeholder="username">
</div>
<div class="avatars">
<button type="button" onclick="chooseanav()" class="female-av-button" name="button"><div class="female-av"></div></button>
<button type="button" class="male-av-button" name="button"><div class="male-av"></div></button>
</div>
<!-- <div class="avatars">
<div class="silhos">
<img src="img/male-avatar-silhouette.png" class="avatar-silho" alt="male avatar silho">
<img src="img/female-avatar-silhouette.png" class="avatar-silho" alt="female avatar silho">
</div>
<div class="avas">
<img src="img/male-avatar.png" class="avatar" alt="male avatar">
<img src="img/female-avatar.png" class="avatar" alt="female avatar">
</div>
</div> -->
<script type="text/javascript">
// document.getElementsByClassName("user-input").style.height="500px";
function chooseanav() {
document.getElementsByClassName('female-av').style.background = "url('../img/female-avatar.png') no-repeat";
}
</script>
</body>
</html>
Any help is greatly appreciated.
Thanks!
Change your code to be;
document.getElementsByClassName('female-av')[0].style.background = "url('../img/female-avatar.png') no-repeat";
Oddly, unlike .getElementById() when you use .getElementsByClassName() you need to index the object. I think this is because IDs are unique where classes can be many.
The clue is in the getElement vs getElements.
EDIT: to answer your comment regarding clicking outside it etc you will have to change up your code a bit. Check my snippet below and let me know if anything doesn't make sense!
body{
margin: 0;
padding: 0;
box-sizing: border-box;
background-color: black;
}
.avatars{
justify-content: center;
margin-left: 15%;
display: flex;
}
.choose-a-user-text{
font-family: 'Luckiest Guy';
font-size: 400%;
justify-content: center;
}
.choose-a-username{
margin-left: 25%;
}
.user-input{
margin-left: 29%;
}
.user-input:focus{
outline: none;
}
.female-av-button{
background: none;
border: none;
padding: 1px;
}
.female-av-button:focus{
}
.male-av-button{
background: none;
border: none;
padding: 1px;
}
.female-av{
background: url('../img/female-avatar-silhouette.png') no-repeat;
width: 500px;
height: 700px;
}
.female-av:hover{
background: url('../img/female-avatar.png') no-repeat;
width: 500px;
height: 700px;
}
.male-av{
background: url("../img/male-avatar-silhouette.png") no-repeat;
width: 500px;
height: 700px;
}
.male-av:hover{
background: url("../img/male-avatar.png") no-repeat;
width: 500px;
height: 700px;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Choose Your Character</title>
<link rel="stylesheet" href="css/avatar-page.css">
<link href="https://fonts.googleapis.com/css2?family=Luckiest+Guy&display=swap" rel="stylesheet">
</head>
<body>
<div class="choose-a-username">
<h2 class="choose-a-user-text" style="color: #018D94;">CHOOSE A USERNAME</h2>
<input class="user-input" type="text" name="" value="" placeholder="username">
</div>
<div class="avatars">
<button type="button" class="female-av-button" name="button"><div class="female-av"></div></button>
<button type="button" class="male-av-button" name="button"><div class="male-av"></div></button>
</div>
<!-- <div class="avatars">
<div class="silhos">
<img src="img/male-avatar-silhouette.png" class="avatar-silho" alt="male avatar silho">
<img src="img/female-avatar-silhouette.png" class="avatar-silho" alt="female avatar silho">
</div>
<div class="avas">
<img src="img/male-avatar.png" class="avatar" alt="male avatar">
<img src="img/female-avatar.png" class="avatar" alt="female avatar">
</div>
</div> -->
<script type="text/javascript">
var femaleAV = document.getElementsByClassName('female-av')[0];
var maleAV = document.getElementsByClassName('male-av')[0];
document.addEventListener('click', function(e) {
if (e.target.className == 'female-av') {
femaleAV.style.background = "url('../img/female-avatar.png') no-repeat";
maleAV.style.background = "";
} else if (e.target.className == 'male-av') {
femaleAV.style.background = "";
maleAV.style.background = "url('../img/male-avatar.png') no-repeat";
} else {
femaleAV.style.background = "";
maleAV.style.background = "";
}
});
</script>
</body>
</html>
Basically, I have removed your onclick="" event from the female-av and have put an overall listener in the <script>. From here I have set 2 variables (Female & Male) and then an if-statement to check what is being clicked. Depending on what is being clicked it will either set/unset the female or male background respectively and if neither of the two are clicked it resets both.
There is a downside to this though, should the user click ANYWHERE else it means it will reset the selection. Example, if you select your MALE or FEMALE and then click to change your username you will see it deselects/resets.
To fix this, you can narrow the function like so;
document.querySelector('.avatars').addEventListener('click', function(e) {...})
That way it only listens to clicks inside the .avatars box.
I hope it's clear! If not, let me know and I'll try explain further!
You don`t have to use javascript to change it. You can use :focus directly in css.
.male-av:focus{
background: url("../img/male-avatar.png") no-repeat;
width: 500px;
height: 700px;
}
.female-av:focus{
background: url('../img/female-avatar.png') no-repeat;
width: 500px;
height: 700px;
}
So this way when the button is clicked you can keep the image or change the background color.But it returns to normal when clicked outside of the button.
This will make any element that has class female-av change its background on click
let fa = document.getElementsByClassName("female-av-button");
for(let i = 0;i<fa.length;i++){
fa[i].addEventListener('click',function(){
this.style.background="url('../img/female-avatar.png') no-repeat";
});
}
if you want only one specific element to have this behavior give it an id and use
document.getElementById("elementID").addEventListener('click',function(){this.style.background="black";});
Maybe have the image contained in the button itself and not the CSS.
Then have a JavaScript function that changes the image.
Or (the easier option) have a JS function that toggles the class containing the new image and the one with the old image (with the old image class already in there).
Say...
<html>
<style>
/* add this to <style> the css (exept the image links) */
.confirm {
background: url('https://live.staticflickr.com/7057/7119974123_291cac34b7_b.jpg') no-repeat;
}
.unclicked {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/8/84/Flag_of_Tabajd_%281-1_aspect_ratio%29.svg/480px-Flag_of_Tabajd_%281-1_aspect_ratio%29.svg.png') no-repeat;
}
</style>
<script>
/*add this to <script> block*/
function change() {
var btnImg= document.getElementById("btn")
btnImg.classList.toggle("confirm")
btnImg.classList.toggle("unclicked")
}
</script>
<div id="Copy this"></div>
<button class="unclicked" id="btn" onClick=change()></button>
</html>
The classes are so the background can be swapped and clicking it twice will result in the original image showing!
It does work for me, so I hope this helps!
Gypsy.jpg location (uploaded)
This will work:
//CSS
button {
background: blue;
}
<!-- HTML and JS -->
<!-- Blue to Gypsy.jpg -->
<button id="this" onclick="putimage('https://i.stack.imgur.com/8oMX9.jpg'); //<-- paste image here.">Click Me!</button>
<script>
var putimage = function(i) {
// i is image url.
document.getElementById("this").style = 'background: url("' + i + '") space !important';
};
</script>

Is it possible to make a image search filter just using Javascript?

In this html file ,I would like to add a image search filter functionality. For example, there are three images which consists of one Naruto image, one Superman image and one Batman image.
So, I would like to add the functionality like when I type "N or n" ,only the Naruto image shows hiding the other two and same for the rest two.
I think making the images run through an array would work but couldn't do so for images and I have seen many youtube videos but most of them use jQuery,electron but I would like to use only Javascript.
The file screenshot and the code(HTML and CSS) are given below:
sample image
HTML:
<body>
<div class="container">
<div class="searchbox_container">
<div class="searchbox">
<input type="text" name=" " placeholder="Search" class="search">
</div>
</div>
<div class="image_container">
<img src="images/naruto.png" alt=""
class="actionimages">
<img src="images/batman.png" alt=""
class="actionimages">
<img src="images/superman.png" alt=""
class="actionimages">
</div>
</div>
</body>
CSS:
<style>
body {
background-color: black;
}
.container {
width: 700px;
height: 400px;
border: 2px solid yellow;
margin: auto;
background-color: black;
}
input {
border: 2px solid darkgoldenrod;
background-color: yellow;
border-radius: 2px;
width: 100px;
height: 10px;
padding: 0 10px;
font-size: smaller;
color: black;
}
.searchbox {
float: right;
margin-top: 5px;
margin-right: 5px;
}
.image_container
{ width:300px;
border:2px solid yellow;
clear:both;
margin:0 auto;
margin-top:50px;
}
.image_container img{
width:90px;
margin-right:auto;
}
</style>
Pardon for any mistakes.Thank you.
This is what I understood from your comments
Fiddled here
var input=document.querySelector('.search');
var images=document.querySelectorAll('.image_container > img');
input.addEventListener('keydown',function(){
for(var i=0; i<images.length;i++)
{
if(new RegExp(this.value).test(images[i].src))
{
images[i].style.display ='block'
}
else
{
images[i].style.display ='none'
}
console.log(images[i].src)
}
})
in short you can use javasscript to search for image.
how you implement the search however is up to you.
one way to do so is to use data attribute for your images data-tags="naruto" and data-tags="batman" and so on.
As you can see in the example below I created an attribute for tags and added the names you want to the tags such as batman image has batman tag attribute.
Then in the javascript I get all the images when the user enters something into the search text box and loop through those images.
in the loop first i hide every image then check with the if statement if the image tag has the searched text in it by using indexOf if the tag has the search text then I show the image
function search(){
var searchText = document.getElementById("searchInput").value;
var images = document.querySelectorAll(".image_container > img");
if(searchText.length > 0){
images.forEach((image) => {
image.classList.add("hide");
if(image.dataset.tags.indexOf(searchText) > -1){
image.classList.remove("hide");
}
});
}else{
images.forEach((image) => {
image.classList.remove("hide");
});
}
}
body {
background-color: black;
}
.container {
width: 700px;
height: 400px;
border: 2px solid yellow;
margin: auto;
background-color: black;
}
input {
border: 2px solid darkgoldenrod;
background-color: yellow;
border-radius: 2px;
width: 100px;
height: 10px;
padding: 0 10px;
font-size: smaller;
color: black;
}
.searchbox {
float: right;
margin-top: 5px;
margin-right: 5px;
}
.image_container
{ width:300px;
border:2px solid yellow;
clear:both;
margin:0 auto;
margin-top:50px;
}
.image_container img{
width:90px;
margin-right:auto;
}
.hide{
display:none;
}
<div class="container">
<div class="searchbox_container">
<div class="searchbox">
<input type="text" name=" " placeholder="Search" class="search" id="searchInput" onkeyup="search()">
</div>
</div>
<div class="image_container">
<img data-tags="naruto" src="https://img.freepik.com/free-psd/3d-gold-logo-mockup-facade-sign_204971-162.jpg?size=664&ext=jpg" alt=""
class="actionimages">
<img data-tags="batman" src="https://img.freepik.com/free-photo/side-view-man-dancing_23-2148666505.jpg?size=664&ext=jpg" alt=""
class="actionimages">
<img data-tags="superman" src="https://img.freepik.com/free-vector/beautiful-floral-invitation-card-template_21799-4192.jpg?size=664&ext=jpg" alt=""
class="actionimages">
</div>
</div>

JavaScript - Swap colors

In this JavaScript example when user clicks on 'Change colors' button, it need to swap colors of two div elements. But it doesn't.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style>
#first
{
border-radius: 100%;
background-color: red;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
#second
{
border-radius: 100%;
background-color: green;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
</style>
</head>
<body>
<button id="color">Change colors</button>
<br />
<div id="first">Random text.</div>
<div id="second">Random text.</div>
<div id="third"></div>
<script type="text/javascript">
document.getElementById('color').onclick = function () {
var divColor = document.getElementById('first').style.backgroundColor;
document.getElementById('first').style.backgroundColor = document.getElementById('second').style.backgroundColor.toString();
document.getElementById('second').style.backgroundColor = divColor.toString();
}
</script>
</body>
</html>
But when I change it a little bit and remove 'background-color' from <style> and put it within <div> then it's working.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style>
#first
{
border-radius: 100%;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
#second
{
border-radius: 100%;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
</style>
</head>
<body>
<button id="color">Change colors</button>
<br />
<div id="first" style="background-color: red;">Random text.</div>
<div id="second" style="background-color: green;">Random text.</div>
<script type="text/javascript">
document.getElementById('color').onclick = function () {
var divColor = document.getElementById('first').style.backgroundColor;
document.getElementById('first').style.backgroundColor = document.getElementById('second').style.backgroundColor.toString();
document.getElementById('second').style.backgroundColor = divColor.toString();
}
</script>
</body>
</html>
So is there any way to make it works for solution when 'background-color' is within <style> in <head>?
Element.style only applies to styles within the style attribute of the element. If you want the computed style, which factors in stylesheets and the like...
var firstElem = document.getElementById('first'),
secondElem = document.getElementById('second'),
firstBackground = window.getComputedStyle(firstElement).backgroundColor,
secondBackground = window.getComputedStyle(secondElement).backgroundColor;
firstElem.style.backgroundColor = secondBackground;
secondElem.style.backgroundColor = firstBackground;
This should swap the two colours, regardless of where they are defined.
For this case it whould be more common to use 3 classes in css. One for defining the common style of the divs. And two for defining the differences. Switching the appearance in that case whould just require switching of classes. Such a set-up is far more flexible also for example in combination with annimations.
A way to alter style using Javascript, without inline styling:
https://jsfiddle.net/6tyw211s/10/
<html>
<style>
#first
{
border-radius: 100%;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
#second
{
border-radius: 100%;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
.color{
background-color: red;
}
.color1{
background-color: green;
}
</style>
<body>
<input type="button" id="color" value="Change colors" />
<br />
<div id="first">Random text.</div>
<div id="second">Random text.</div>
<div id="third"></div>
</body>
<script>
var y= document.getElementById('color');
var f=document.getElementById('first');
var s=document.getElementById('second');
y.addEventListener('click', function(){
if (f.className === "color1") {
f.className = "color";
}
else {
f.className = "color1";
}
if(s.className==="color"){
s.className="color1";
}
else{
s.className="color";
}
})
</script>
</html>
You can use switchClass() in jqueryui to do it.
That way, you don't have to specify the background-color values to the divs.
$("#color").click(function myFunction() {
$(".first").switchClass("first", "second", 200, "easeInOutQuad");
$(".second").switchClass("second", "first", 200, "easeInOutQuad");
});
Here is a working version with jqueryui
http://api.jqueryui.com/switchclass/

Categories