I try to make each of them separated.
<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">This will change b element</div>
<div id="b">This is element b</div>
<div id="f" onmouseover="chbg('blue')" onmouseout="chbg('white')">This will change g element</div>
<div id="g">This is element g</div>
<div id="j" onmouseover="chbg('yellow')" onmouseout="chbg('white')">This will change k element</div>
<div id="k">This is element k</div>
Here is JS
function chbg(color) {
document.getElementById('b').style.backgroundColor = color;
document.getElementById('g').style.backgroundColor = color;
document.getElementById('k').style.backgroundColor = color;
}
Doesn't work properly here http://jsfiddle.net/qUzn5/ .
You might want to put a second argument in your function like this:
JavaScript:
function chbg(color, id) {
document.getElementById(id).style.backgroundColor = color;
}
HTML:(Repeat the div's)
<div id="a" onmouseover="chbg('red', 'a')" onmouseout="chbg('white')">This will change b element</div>
Currently they all get colored because the function calls each of the ids
I guess you should add a variable to your javascript function. This variable contains the id of the element to be changed.
I do not know anything of javascript, but i guess it should look like this:
function chbg(id,color) {
document.getElementById(id).style.backgroundColor = color;
}
You tagged this with jQuery so I'm going to assume you're using that. If so, cut down your code a bit like this...
$('#b').css('background-color', color);
If you're using jquery you shouldn't need to use getElementById and .style.
http://api.jquery.com/css/#css2
And since your function has everything in it, each background will change.
If you must use javascript instead of CSS, try passing a different argument to your function. Perhaps the ID of the background that should change. Then set conditionals in your function according to what ID is passed.
if ( divId == 'b ) {
Code to change b div
}
Related
I'm trying to change the style of a div with vanilla JS. The div should have a certain id and the class name tab-content:
function showTabContent() {
document.getElementById(tabID).classList.contains("tab-content").style.display = "block";
}
HTML:
<div id="1" class="tab-content">Test...</div>
<div id="2" class="tab-content">Test...</div>
<div id="3" class="tab-content">Test...</div>
If for example I run:
showTabContent(2);
It should set the tab-content div with id 2 to style display block. It is not working. What am I doing wrong?
First of all you should pass tabID to your function.
.containe() method in JavaScript shows whether a string has a specific word or letter and if the condition is true, it will return true. (boolean)
if you want to get the element with a specific ID and tab-content class, you can work with querySelector.
document.querySelector("#"+tabID+".tab-content").style.display="block"
But since ID is most often unique, referring to the ID alone is sufficient.
document.getElementById(tabID).style.display="block"
is the code pasted is right from the source code.
The above function showTabContent() should accept argument.
showTabContent(tabId)
Since you are passing the id to function showTabContent then you can receive it using parameter i.e tabId.
then you have to find the element and check for its existence. It could be possible that the element with specified id is not present.
function showTabContent(tabId) {
const element = document.getElementById(tabId);
if (element) {
element.style.display = "block";
element.style.backgroundColor = "lime"; // FOR VISUAL PURPOSE ONLY
}
}
showTabContent(2);
<div id="1" class="tab-content">Test...</div>
<div id="2" class="tab-content">Test...</div>
<div id="3" class="tab-content">Test...</div>
I would like to be able to change the color of a gridbox at runtime based on the text in the box. I have a JS function called checkColor(str) which will return a color but I can't figure out the correct syntax to get it to work.
<div class="grid-item" style="background-color:checkColor(Swim)">
{{bunk.activities[_-1]}}
</div>
<script>
function checkColor(s){
if (s == "Swim"){
return 'red'
}
}
</script>
There is no CSS syntax for calling a JavaScript function. You need to approach this from the JavaScript end.
Possibly you should set up a DOM Ready event listener which will get all the divs you care about and then loop over them accessing their style properties to set the colour you want. Since you would need to get "Swim" from somewhere you might want to use a data attribute.
That said, it would probably better to just forget about JS entirely for this and use a class instead.
class="grid-item swim">
and
.grid-item.swim { background-color: red; }
Well, you can not add js function in style attribute! Instead, you need to change the background using JavaScript & CSS:
var element = document.getElementById("item_1");
element.classList.add("swim");
.swim{
background-color: red;
}
<div id="item_1" class="grid-item">
Hello World
</div>
Above we injected a class name 'swim' that has a style of red background.
You can do it this way, if you set the value to check as "data-value".
Loop all elements with class grid-item, if "data-value" == Swim apply color.
function checkColor(s,item){
if (s == "Swim"){
item.style.backgroundColor = "red";
}
}
var item = document.getElementsByClassName('grid-item')
for (var i in item){
checkColor(item[i].getAttribute('data-value'),item[i])
}
<div class="grid-item" data-value="Swim">
{{bunk.activities[_-1]}}
</div>
<div class="grid-item" data-value="Swim">
{{bunk.activities[_-1]}}
</div>
`function checkColor(s){
if (s == "Swim"){
return 'red'
}
}
document.getElementsByClassName('grid-item').style.background = checkColor("Swim");
`
This should set "grid-item"'s background to red
you cant call java script function from CSS rather than that i suggest to you to use java script and make switch with all colors and item names.
function checkColor(){
var elements = document.getElementsByClassName();
for(var x = 0;x < elements.length;x++){
switch(elements[x].innerHtml){
case 'swim':{
elements[x].style.background = 'red';
break;
}
.
.
.
.
}
}
}
I am creating a website where elements can be dragged and dropped from the main div with all the elements to an empty one. After you put two or more elements in the second (empty) div, you press a button which executes an if/else statement, but I want it so that the code does something if element10 and element12 are in the div, but something different if element4, element5, and element6 are in the div. Could someone help?
I would add some data to the DIVs and then use it inside of the function you just mentioned.. I think if you give enough data, you can make a dynamic call based on those data. ( or add call backs )
so for example you have this as html:
<div class="parent">
<div class="drag-able" data-name="element1" ></div>
<div class="drag-able" data-name="element2" ></div>
<div class="drag-able" data-name="element3" ></div>
<div class="drag-able" data-name="element4" ></div>
</div>
then you will have something like that in your function
//by "this" I assume you have your dragging function
switch(this.getAttribute('data-name')){
case 'element1':
// do your code
break;
case 'element2':
// do your code
break;
default : // do other code
break;
}
in fact is a little dirty but if you could provide more info and some code I could help you better. but I hope it gives you some idea about what I tried to explain.
You could track the elements using ids.
Something like this for your JavaScript, assuming that you aren't using jquery:
var if_else = function(){
var box = document.getElementById("dropIn");
var elements = box.getElementsByTagName('div');
var elm1 = elements[0];
var elm2 = elements[1];
if(elm1.id === "suchAndSuch" && elm2.id === "soAndSo"){
// do something
}
else{
//do something else
}
}
And for your HTML:
<div id="box"></div>
<div id="suchAndSuch"></div>
<div id="soAndSo"></div>
<div id="somethingElse"></div>
So I have this HTML:
<div class="tip-box">
<div class="tip-title" onclick="toggleTip()">
<h2>Tip 1</h2>
</div>
<div class="tip-content hidden">
<p>Tip 1 content</p>
</div>
</div>
And this Javascript:
function toggleTip() {
$(this).siblings(".tip-content").toggleClass("hidden");
}
Hopefully it's obvious what this is supposed to do, but it doesn't work. Using .siblings() just doesn't seem to work in this way.
What's the correct solution for this? To get the next sibling of a certain type or with a certain class and then hide/show it?
You can use Jquery function.
<div class="tip-box">
<div class="tip-title">
<h2>Tip 1</h2>
</div>
<div class="tip-content hidden">
<p>Tip 1 content</p>
</div>
</div>
$(document).ready(function(){
$('.tip-title').click(function(){
$(this).siblings(".tip-content").toggleClass("hidden");
});
});
you can also use this
<div class="tip-box">
<div class="tip-title" onclick="toggloTip(this)">
<h2>Tip 1</h2>
</div>
<div class="tip-content hidden">
<p>Tip 1 content</p>
</div>
</div>
<script>
function toggloTip(elm) {
$(elm).siblings(".tip-content").toggleClass("hidden");
}
</script>
You can use pure javaScript with nextElementSibling property of node something like below,
I suppose you want do this operation with siblings.
function getChildrens(n, selector) {
var nodes = [];
while (n.nextElementSibling != null) {
if (n.nextElementSibling.hasOwnProperty('classList')) {
if (n.nextElementSibling.classList.contains(selector)) {
//return n.nextElementSibling;
nodes.push(n.nextElementSibling);
}
}
n = n.nextElementSibling;
}
return nodes;
};
function getSiblings(n, selector) {
return getChildrens(n, selector);
}
function toggleTip(elem) {
var siblings = getSiblings(elem, "tip-content");
if (siblings.length > 0) {
for (var i = 0; i < siblings.length; i++) {
siblings[i].classList.toggle("hidden");
}
}
}
.hidden {
display: none;
}
<div class="tip-box">
<div class="tip-title" onclick="toggleTip(this)">
<h2>Tip 1</h2>
</div>
<div class="tip-content hidden">
<p>Tip 1 content</p>
</div>
</div>
Here is another non JQuery answer.
To get the next element sibling use:
var nextElement = element.nextElementSibling;
To get the previous element sibling use:
var previousElement = element.previousElementSibling;
To get the element index use:
var index = Array.prototype.slice.call(element.parentElement.children).indexOf(element);
If you are at the first element the previousElementSibling value will be null.
If you are at the last element the nextElementSibling value will be null.
How about this JavaScript:
$(function(){
$('.tip-box').on('click', '.tip-title', function(){
$(this).next('.tip-content').toggleClass('hidden');
});
});
Remove the idea of working with onclick attributes when you use jQuery.
None of the previous answers, not even that serial-upvoted one ;), actually explains the problem and why their solutions work.
The problem is that an inline onclick handler does not pass on its current context. Inside the onclick="" JavaScript code this is the element clicked. Once you call a global function (like your toggleTip), that context is lost. The this the function receives is window and not the element.
The usual quick fix, for raw JavaScript code, is to pass this as a parameter to the global function.
e.g.
onclick="toggleTip(this)"
and receive a parameter in the function like this:
function toggleTip(element) {
$(element).siblings(".tip-content").toggleClass("hidden");
}
However, as you are using jQuery, inline event handlers are actually a bad idea. They separate the event registration from the event handler code for no reason and do not allow for multiple event handlers, of the same type, on the same element. They also bypass the rather cool event bubbling system jQuery uses.
The preferred alternative, with jQuery, is to use jQuery to select the element and jQuery to connect the event in one step:
jQuery(function($){
$('.tip-title').click(function(){
$(this).siblings(".tip-content").toggleClass("hidden");
});
});
As you only want the element that follows, and potentially will add more pairs, the better option would be using nextAll and first(), with the same jQuery filter, instead of siblings:
e.g.
jQuery(function($){
$('.tip-title').click(function(){
$(this).nextAll(".tip-content").first().toggleClass("hidden");
});
});
Or, of you can guarantee it is the next element, use next as #Tim Vermaelen did (with or without the selector makes no difference, so might as well leave it out):
jQuery(function($){
$('.tip-title').click(function(){
$(this).next().toggleClass("hidden");
});
});
Note: In this example jQuery(function($){ is a DOM ready event handler which is the rather handy shortcut version of $(document).ready(function(){YOUR CODE});, which also passes a locally scoped $ value. For those that mistake this code for an incorrect IIFE, here is a working example: http://jsfiddle.net/TrueBlueAussie/az4r27uz/
I'm new to Javascript and am attempting to write a function that changes the color of some text, however "this" keeps returning as undefine, and not changing the text color.
Here's the code, I would greatly appreciate some help.
<h1>
<ul><div class="info" id="info" onclick="this.style.color= '#9DC8BA'">INFO
</div></ul>
<ul><div class="menu" id="menu" onclick="test1()"<!--this is where the problem is-->MENU</div></ul>
Here's the Javascript
function test1() {
this.style.color= '#9DC8BA';
}
you have to pass the reference of the DOM element to the function
<div class="menu" id="menu" onclick="test1(this)">/div>
in the above html, this refers the current DOM element which is a DIV of id menu.
and then refer and modify the DOM inside the function
function test1(obj) {
obj.style.color= '#9DC8BA';
}
Side note: You seem to be having a same name for class and id for the div, which is not a good practice.
Always remember Class corresponds to a group of elements and ID corresponds to unique elements.
test1 function is executed not on the div element as context but on window.
do this:
onclick="test1(this)"
in function:
function test1(div) {
div.style.color = '#9DC8BA';
}
Html Code
<h1>
<ul><div class="info" id="info" onclick="this.style.color= '#9DC8BA'">INFO
</div></ul>
<ul><div class="menu" id="menu" onclick="test1(this)">MENU</div></ul>
</h1>
JavaScript Code:
function test1(obj)
{
obj.style.color= '#9DC8BA';
}
When you are writing onclick inside the html, it makes new function itself.
In your case it is something like function(){test1()}. this inside this function is what you need, but this inside the test1 is undefined.
You can use this as argument of test1
... onclick="test1(this)" ...
and JS
function test1(obj) {
And use obj instead of this in test1
Or set function onclick attribute from javascript like:
var menu = document.getElementById('menu');
menu.onclick = test1;
In this case this inside the test1 will be exactly what you need.