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.
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 have a div in jquery template and I want to call a javascript function from template. e.g.
My div in jquery template is as follows:
<div class="div1" ${makeContainer(this)}>
</div>
'makeContainer' is a function in javascript. I am unable to pass the reference of current element i.e. 'div1' in 'this' parameter.
Please help
You can select all div with class div1 and call function for each element.
$('.div1').each(function(){
makeContainer($(this));
});
So in html you can just use
<div class="div1"></div>
Not sure about your requirement. Do you mean to pass the reference of div?
Anyway I have created a demo which may be useful to you
HTML
<div id = "div_1" onclick="myDemoFunc(this)">Hello
</div>
JS
function myDemoFunc(elem){
var getElem = elem;
var id= getElem.id;
alert(id);
}
WORKING COPY
Try this:
<div class="div1"></div>
And JS Code:
<script type="text/javascript">
$(document).ready(function(){
$('.div1').each(function(){
makeContainer($(this));
});
});
function makeContainer(value)
{
console.log(value);
}
</script>
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 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
}
i have an element and i want to alert the class attribute of this element i use this code;
<li id="SSS" class="settings" onclick="alertClassName(this)">1111</li>
and in the alertClassName function ;
function changeClass(elem)
{
var x = $(elem.id);
alert(x.class) ;
}
it alerts undefind.
Try with className instead of class.
onclick="alertClassName(this)"
...
function alertClassName(elem) {
alert(elem.className);
}
Reference.
First off, you have to decide on a function name (alertClassName or changeClass). I'll use alertClassName as that matches the question title:
Here:
<li id="SSS" class="settings" onclick="alertClassName(this)">1111</li>
...you're passing a reference to the actual element into your function. The this within the code in an onxyz DOM0 handler attribute refers to the element the onxyz attribute is on.
This means you can just use it directly:
function alertClassName(elem)
{
alert(elem.className);
}
And if you wanted to change it:
<li id="SSS" class="settings" onclick="changeClass(this, 'foo')">1111</li>
and
function changeClass(elem, newClass)
{
elem.className = newClass;
}
...would remove all classes from the element when it was clicked and add the foo class.
You can access class name directly via className property (no need for jQuery, in this case):
function alertClassName(elem)
{
alert(elem.className);
}
You trying to activate different function then what you posted) alertClassName instead of changeClass )
Here's an example of how to alert and then change the class of your element. (here's the fiddle).
And the code:
<li id="SSS" class="settings" onclick="changeClass(this)">1111</li>
<script>
function changeClass(e)
{
alert("Current Class:" + e.className);
e.className = "Settings2";
alert("Updated Class:" + e.className);
}
</script>
try:
alert($(this).attr('class'))