How can I change a div class name when clicking on it? Eg:
<div class="first_name" onclick="changeClass();" id="first_name"></div>
I want to change it as follows, when a user clicks on the div
<div class="second_name" onclick="changeClass();"></div>
I wrote the JavaScript as:
<script language="javascript">
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name")
NAME.className="second_name"
}
</script>
It's working for the first instance only. That is on page load, if I click on it, the first_name gets changed into second_name. But clicking on it again, it won't revert the second_name to first_name.
You have to define the second class name. Currently, you have got a function which changes the class name to a hard-coded value, independent on the current class name. See also: MDN: if...else
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name");
var currentClass = NAME.className;
if (currentClass == "second_name") { // Check the current class name
NAME.className = "first_name"; // Set other class name
} else {
NAME.className = "second_name"; // Otherwise, use `second_name`
}
}
A quite late answer, but the reaction marked as answer can be shortened:
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name");
NAME.className = (NAME.className == "second_name") ? "first_name" : "second_name";
}
This is a shortened notation of the if-else structure. It checks if the className is equal to "second_name".
If it is, the currentClass variable will become "first_name", if it's not (meaning it's "first_name"),
it will become "second_name".
simple javascript function, put it in your application.js, or script tag :-
(jQuery should be included to run the following function)
function changeClass(){
$("#first_name").attr("class", "class-name-you-want-to-assign");
}
That's because there is no code to do so. Add a little check. I also added some semicolons. I wonder if your script would even work the first time.
<script language="javascript">
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name");
if (NAME.className==="second_name")
{
NAME.className="first_name";
}
else
{
NAME.className="second_name";
}
}
</script>
You have to use an if-statement to reverse it. Here's an example:
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name")
var currentClass = NAME.className;
if(currentClass == "second_name"){
NAME.className = "first_name";
} else {
NAME.className = "second_name";
}
}
Related
I would like to run different functions depending if a field is checked or not during page load.
So I use window.onload. The first if condition works great but I would like to add more if conditions as defined below. But it doesn't seem to be the proper way.
I thought I could work with if and if else. Does someone know how to make multiple if conditions work for window.onload function?
<script>
window.onload=function(){
if (document.getElementById("field1").checked) {
document.getElementById("field2").style.color = "red";
}
else if (document.getElementById("field3").checked) {
document.getElementById("field4").style.color = "red";
}
<script>
Added: I would like to add that all functions must be executed if all the if statements are fitting (so if else functions are maybe incorrect in this context). If only field1 is fitting the conditions, only the matching field2 should turn colour of text into red.
It’s not about the colour (that’s just an example for a JS function) - in real I want 3 things: enter value X, turn red and get disabled for future inputs (I already coded that - so not necessary).
UPDATE: Thanks to your comments. I used the code of Emiel Zuurbier: It's working for field 1 until 4 but not for field 10 until 14, did I wrote it wrong?
<script>
const fieldMap = [
['field1', 'field2', 'field3', 'field4'],
['field10', 'field11', 'field12', 'field14']
];
window.onload = function() {
for (const [fieldA, fieldB, fieldC, fieldD] of fieldMap) {
if (document.getElementById(fieldA).checked) {
document.getElementById(fieldB).value = "X";
document.getElementById(fieldB).style.color = "red";
document.getElementById(fieldB).disabled = true;
document.getElementById(fieldC).value = "X";
document.getElementById(fieldC).style.color = "red";
document.getElementById(fieldC).disabled = true;
document.getElementById(fieldD).value = "X";
document.getElementById(fieldD).style.color = "red";
document.getElementById(fieldD).disabled = true;
}
}
}
</script>
You can eleminate repeating tasks by taking the dynamic parts of your code, in this case your ID selectors, and put them in an array (or object) which you can loop over.
const fieldMap = [
['field1', 'field2'],
['field3', 'field4']
];
window.onload = function() {
for (const [fieldA, fieldB] of fieldMap) {
if (document.getElementById(fieldA).checked) {
document.getElementById(fieldB).style.color = 'red';
}
}
}
The principle of writing your code like this is called DRY (Don't Repeat Yourself)
winow.onload executes your function() when the page is fully loaded, but it happens just once. If the code you provided is correct then I think you might be missing } at the end. However, there's still one thing that bothers me. If you check if a specified checkbox is checked it checks the checked property only when the page is fully loaded, not when the user clicks on the #field checkbox. If you want the check whether the user checked the checkbox then you can use eventlistener 'check'.
I have a simple form (text field and submit button). I am trying to have the user submit a number, and the resulting number will display one div (from a set of divs).
I tried using this example as a base (when the user clicks a link, it shows a div, but hides others).
My test is below:
var divState = {};
function showhide(oFrm) {
var dividnum = oFrm.Inputed.value;
var prepar = "para";
var divid = prepar + theInput; /* should result in something like "para52" */
divState[divid] = (divState[divid]) ? false : true;
//close others
for (var div in divState){
if (divState[div] && div != divid){
document.getElementById(div).style.display = 'none';
divState[div] = false;
}
}
divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
}
http://jsfiddle.net/LfzYc/431/
Note: I am NOT proficient in JavaScript at all, which is why I am having difficulty.
Also, I'd like to add a function ... if the number entered is not between 1-4, show a different div, maybe with the id paraEnd.
Please look at the jsFiddle based on your one. I hope I've done what you want. I changed the showhide function and your HTML (fixed div's IDs and added one more div#paraEnd). I'd suggest you refactoring your code.
You should use jQuery to have an easy way to manipulate the DOM.
Using jQuery I made an example for you, just change your JS and paste mine:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
(function ($) {
// get the paragraphs
var paragraphs = $('.paragraph');
// form submit
$('#paragraphform').submit(function (e) {
// prevent the event to flow
e.preventDefault();
// get the input value
var value = $('#Inputed').val() - 1;
// reset all divs removing active css class
paragraphs.removeClass('active');
$('.error').removeClass('active');
// verify if the value doens't exist
if(value < 0 || value > paragraphs.length - 1) {
$('.error').addClass('active');
return;
}
// show the active div
paragraphs.eq(value).addClass('active');
});
})(jQuery);
</script>
Is that what you need?
If you not familiar with jQuery, this is the jquery Learn Center:
https://learn.jquery.com/
And this is a nice tutorial for beginners:
http://www.tutorialspoint.com/jquery/
I want to execute a function repeatedly on groups of predictably named html divs.
I am using a drag and drop relationship shown below in which dragging text into a certain div space "target" causes that text to appear in another div called "saves".
<script type="text/javascript">
function OnDragStart (event) {
if (event.dataTransfer) {
var format = "Text";
var textData = event.dataTransfer.getData (format);
}
}
function OnDropTarget (event) {
if (event.dataTransfer) {
var format = "Text";
var textData = event.dataTransfer.getData (format);
if (!textData) {
textData = "<span style='color:red'>The data transfer contains no text data.</span>";
}
var savesDiv = document.getElementById ("saves");
savesDiv.innerHTML = savesDiv.innerHTML + "<br />" + textData;
}
else {
alert ("Your browser does not support the dataTransfer object.");
}
if (event.stopPropagation) {
event.stopPropagation ();
}
else {
event.cancelBubble = true;
}
return false;
}
</script>
The script in combination with the corresponding html works perfectly for the target and saved divs... but what i would really like is to apply the same script to a set of divs pairs named
(target1, saves1 )
(target2, saves2)
(target3,saves3)
(target4 saves4) etc etc
with numbers in div ids going up every time by 1 up to (target20, saves 20) ... Without obviously repeating the same script 20 times with different id names when referring to all the target and saved divs.
I realize this is a total newbie question but I'm really interested to learn the different ways this can be approached.
Give a common class name to these divs so when the dragdrop event occurs, it can be handled using the class name instead of the id; that is, like $('.someClass').someEvent instead of $('#target1'). You can get its id property inside this function using $(this).attr("id").
So if you have "target1" as the id, get the last character ("1") using the JavaScript substring function; you can write generic code such as this:
$('.someClass').someEvent(function(){
var id=$(this).attr(id);
var lastno=id.substring(id.lastIndexOf("t"),id.length);
//now rest of code
$("#saves"+lastno).val($("#target"+lastno).val());
});
I want to check if a specific hidden div exists and if not create one.
I do:
function myFunction(somestring) {
var myHiddenDiv = jQuery('<div id="js_method" style="display:none">');
...
myHiddenDiv.append(somestring);
}
The problem is this seems to create a new hidden div every time the function is called on the same page.
the hidden div just seems scoped to the function, whereas I want it scoped to the page.
Any tips.
tips please
Thanks.
Use length property:-
function myFunction(somestring) {
var myHiddenDiv;
if($("#js_method").length == 0){
myHiddenDiv = jQuery('<div id="js_method" style="display:none">');
$("body").append(myHiddenDiv);
}else{
myHiddenDiv = $("#js_method");
}
...
myHiddenDiv.append(somestring);
}
Why not just check by ID?
if (jQuery("#js_method").length == 0) {
var myHiddenDiv = jQuery('<div id="js_method" style="display:none">');
...
myHiddenDiv.append(somestring);
}
I have got a small javascript function and a piece of html code where i have a button, and I want that whenever user hovers that button, a little box to appear.Everything seems to be working great,despite that my function executes only after I hover that button for the 2 time(after the page has just loaded and I try to use my function for the 1 time, later everything executes after a firs hover).So what can I do about it?
HTML code
<body>
<div id = "searchBox">
<p id = "paragraph"><input type = "text" name = "serachBar"/>
<input type = "button" value = "szukaj" name = "search"/>
</p>
<div id = "searchButton">Szukaj</div>
</div>
</body>
and javascript itself
<script type = "text/javascript">
function popUp(menu){
var searchBox = document.getElementById(menu).style;
var searcButton = document.getElementById('searchButton');
if(!searchBox || searchBox.display == "none"){
searchBox.display = "block";
}
else {
searchBox.display = "none";
}
};
</script>
Change your if statement like this:
function popUp(menu) {
var searchBox = document.getElementById(menu);
var searcButton = document.getElementById('searchButton');
if (searchBox) {
if(searchBox.style.display == ""){
searchBox.style.display = "block";
}
else {
searchBox.style.display = "";
}
}
};
The original value will be "" instead of "none".
I'm making the assumption that the CSS setting is to display:"none".
I also moved the searchBox condition. If it isn't found, you don't want to set properties at all.
<p> is a flow element and can't contain <input>s.
Besides, your function instructs to toggle hidden state, rather than show box on mouseover. Therefore, the box will hide on first hover, and reappear on the second one.
You probably want to define mouseover and mouseout event listeners.