Only one function rather than many that are looking the same? - javascript

Bonjour ! here is my question, I'm using, two "kinds" of JS short functions (5 lines of code per function) but I have to make, let's say, about 10 of each kind. It would be a total of 100 lines of code which is very long... So I was wondering if there could be an easy and very shorter way to implement this. I know very very few in javascript and I like roughly understand what I write. (If possible, avoid using JQ, for which I absolutely don't understand a word !)
Here are the functions :
function typedepolice() {
var nodes = document.getElementById('stripid').childNodes;
var nompolice = document.Selections.police.options[document.Selections.police.selectedIndex].value;
for(var i=0; i<nodes.length; i++) {
if (nodes[i].nodeName.toLowerCase() == 'div') {
nodes[i].style.fontFamily = document.Selections.police.options[document.Selections.police.selectedIndex].value;
}
}
}
html calling : ...<select name="police" id="police" size="1" onchange="typedepolice()">...
function colbandeau() {
var nodes = document.getElementById('stripid').childNodes;
var colorFmsg = document.getElementById("colorFmsg").value;
for(var i=0; i<nodes.length; i++) {
if (nodes[i].nodeName.toLowerCase() == 'div') {
nodes[i].style.background = '#' + document.getElementById("colorFmsg").value;
}
}
}
html calling : ...<input id="colorFmsg" class="color3" value="FFFFFF" size="5" onchange="colbandeau()">...
The first one refers to a selected option of a dropdown selection box.
The second one to a color selected with JSColor which is a JS plugin to choose a color.
As you see, they are intended to dynamically change CSS properties of numerous div children of one element which Id is "stripid", and are called by "onchange" events.
After a long search, I found the pattern of these functions in a reply in stackoverflow and they are exactly what I needed. For this, I thank very largely Vijay Agrawal, because it will improve a lot my web page.
NB : don't be afraid, "police" is meaning "font" in French :)
If someone could help me, it would be great !

You can create a function to set the stripid child nodes
function setNodeStyle(value, style) {
var nodes = document.getElementById('stripid').childNodes;
for (var i=0; i<nodes.length; i++) {
if (nodes[i].nodeName.toLowerCase() == 'div') {
nodes[i].style[style] = value;
}
}
}
Then you can call it in the other functions:
function colbandeau() {
setNodeStyle(document.getElementById("colorFmsg").value, "background");
}
This will already save you quite a bit.
You can improve on this even more by setting an attribute that contains the value that is to be. To get you started:
<input class="color3 changer" value="FFFFFF" size="5" data-style="background">
Array.prototype.forEach.call(document.querySelector(".changer"), function (el) {
el.addEventListener("change", function () {
setNodeStyles(this.value, this.dataset.style);
});
});

Related

Two javascript 'changeimage' functions, only one is working

I am learning javascript and I have a problem with changeimage function.
I need to change both one, and second image.
Here is jsfiddle.
https://jsfiddle.net/7ewjoxnv/1/
And here below, javascript:
var switchingImage;
function changeImage()
{
switchingImage.src = this.value;
}
window.onload = function() {
var radios = document.getElementById('imageSwitcher').getElementsByTagName('input');
switchingImage = document.getElementById('imageToSwitch');
for(var i=0;i<radios.length;i++)
{
radios[i].onclick = changeImage;
}
var radios = document.getElementById('imageSwitcher2').getElementsByTagName('input');
switchingImage = document.getElementById('imageToSwitch2');
for(var o=0;o<radios.length;o++)
{
radios[o].onclick = changeImage;
}
}
Any help will be much appreciated.
Best Regards,
David!
When you do var radio = and switchingImage = for the second time, you are changing their previous values.
In the case of radios it just happens and does not affect you because you have already applied the listeners you wanted to the old radio buttons.
In the case of switchingImage however, it affects you, because switchingImage will ultimately point to the document.getElementById('imageToSwitch2'). So when you call changeImage() it will always operate on document.getElementById('imageToSwitch2').
Here's one way you could solve your problem. It is purposefully not the best solution. Use it as a baseline to improve on it.
https://jsfiddle.net/7ewjoxnv/4/

javascript collapsible table without jquery

This is a simple question I can't seem to figure out and every google search returns a million ways to do this via jquery, but I'd prefer to use vanilla javascript because I am new to it and want to learn it well before using any libraries. What I am trying to do is have a button collapse part of a table when clicked and then show those hidden parts again when clicked again. Basically just toggling the display of a class of elements.
I have a button that calls the test() function
when clicked nothing on my table changes. Here is my javascript code. I am using collapse[0] because if I understand it correctly collapse is a nodeList and I always close and open all of these together so I only need to check the first element.
function test() {
var collapse = document.getElementsByClassName("catOne");
var i = 0;//Counter for loops
if(collapse[0].style.display === "table-row"){
for(i = 0; i < collapse.length; i += 1){
collapse[i].style.display = "none";
}
}
if(collapse[0].style.display === "none"){
for(i = 0; i < collapse.length; i += 1){
collapse[i].style.display = "table-row";
}
}
}
I've tested the function with this code:
function test() {
var collapse = document.getElementsByClassName("catOne");
var i = 0;//Counter for loops
for (i = 0; i < collapse.length; i += 1) {
collapse[i].style.display = "none";
}
which works fine on collapsing the elements so evidentally the issue is with my if statement, but my IDE, Netbeans, doesn't throw any errors and as far as I can tell it should be working.
Thanks for the help.
Link to html and javascript: https://jsfiddle.net/ozjbekjy/
I suspect there are a few problems working against you.
First, you need to make sure the test() function is defined earlier in the page than it's being used. With jQuery, that means using the $(function(){}) wrapper to apply event handlers on DOM ready. You can approximate the same thing yourself with something like this answer.
Otherwise, simply place the <script> tag somewhere before the table (probably in the <head>), and the onclick will work.
You also are using i += 1 where you could be using i++ - they accomplish the same behavior.
Secondly, instead of manipulating the style attribute, use the classList.toggle() function to simply add and remove a class that has the rule display: none, like so:
CSS
.hide-me {
display: none;
}
JavaScript
function test() {
var collapse = document.getElementsByClassName("catOne");
for (var i = 0; i < collapse.length; i++) {
collapse[i].classList.toggle("hide-me");
}
}
Your JSFiddle, with the suggested updates: https://jsfiddle.net/ozjbekjy/4/

Javascript hide element(s) and put something else in place

I have a small question.
For a task we have to make in Javascript I need some help.
We have a text and some words we give an id (html). In javascript we have to make a function that when it's clicked, all the words with the id become invisible. I know, I can do this too. But there's one more thing. If we put the word invisible, it has to become clear there was a word there before! It would look like a fill-in text, if you can understand.
Now I have this:
function toggle_woordjes() {
var e = document.getElementsByClassName('invul');
for(i = 0; i < e.length; i++){
if (e[i].style.display !== ''){
e[i].style.display = '';
}
else {
e[i].style.display = 'block';
}
}
}
The code doesn't work properly anymore because I changed it so much that I can't get back to the original.
I hope you people can help me.
Sorry that my English isn't the best!
Cheers
If the parent's background is only 1 color (no design nor pattern), you may write something like the following.
object.style.backgroundColor="same color as parent"
however if the background is more complex:
function toggle_words() {
var doms = document.getElementsByClassName('class_name');
for (var i = 0; i < doms.length; ++i) {
var domStyle = doms[i].style;
if (domStyle.visibility === 'visible') {
domStyle.visibility = 'hidden';
}
else {
domStyle.visibility = 'visible';
}
}
}
I use visibility instead of display because the elements stay in the DOM, thus the user knows there was something before.
For one thing, I think that you need to make it e[i].style.display = 'none'; rather than empty string in order to make them disappear (and change the test accordingly).
But it sounds like that wasn't your real problem but rather displaying text to indicate that there was an element there. I would suggest having a <div> with class 'invul' that contains 2 other <div> elements: 1 is the text to display if the real content is invisible and the other is the real content. Something like this:
<div class="invul">
<div class="msg">Word was here</div>
<div class="word">I am the real message</div>
</div>
Then make them disappear and reappear as needed.

make one element visible and 49 others invisible

I am absolutely new to javascript, so please bear with me.
I have 50 elements on my page with ids. All are set to visibility:hidden and position:fixed. I have a button that corresponds to each element. When a button is clicked, a javascript function is initiated which makes the corresponding element visibile and position:relative. Code looks something like this:
document.getElementById("id1").style.position='relative';
document.getElementById("id1").style.visibility='visible';
To ensure that only one element is ever visible and relative, I also need to make the other 49 elements hidden and fixed. How can I accomplish this without having to resort to the following sort of code:
function makeid1visibile()
{
document.getElementById("id1").style.position='relative';
document.getElementById("id1").style.visibility='visible';
document.getElementById("id2").style.position='fixed';
document.getElementById("id2").style.visibility='hidden';
document.getElementById("id3").style.position='fixed';
document.getElementById("id3").style.visibility='hidden';
document.getElementById("id4").style.position='fixed';
document.getElementById("id4").style.visibility='hidden';
// etc...
}
Any help would be appreciated, because with 50 elements, the number of lines of coding would be outrageous.
Should be able to handle it with a single loop, just pass in the number of the item you wish to show:
function makeIdVisible(id) {
document.getElementById("id" + id).style.position='relative';
document.getElementById("id" + id).style.visibility='visible';
for (var i = 1; i <= 50; i++) {
if (i !== id) {
document.getElementById("id" + i).style.position='fixed';
document.getElementById("id" + i).style.visibility='hidden';
}
}
}
give yours checkboxes classname "someclass" and select all elements by function documet.getElementsByClassName
You can write a function like this:
function makeVisible( id ){
var idList = ['id1','id2','id3','id4'];
for( var i = 0, l = idList.length; i<l ; i++ ){
document.getElementById(idList[i]).style.position='fixed';
document.getElementById(idList[i]).style.visibility='hidden';
}
document.getElementById(id).style.position='relative';
document.getElementById(id).style.visibility='visible';
}
Then you can use
makeVisible('#id1');
to make the id1 element visible

How to change the color of the links with javascript?

I want to know how can I manipulate all the links on a page with javascript. I can get elements by id's with document.getElementById(id), but how can I get the links? And also how can I get all elements with a certain classname? I want to change the color of the link and class elements.
I mean these links:
This is a link
And an example for an element with a class:
<span class="link">This is an element with a class</span>
Please no jquery. I want javascript.
Simple and straightforward (in pure JS too!)
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 = hex;
}
}
}
If it's a class name you're looking for and you know the tag, just use this.
var elements = document.getElementsByTagName("span");
for(var j=0;j<elements.length;j++)
{
if(elements[j].className === "your class here")
{
//do something
}
}
You can also look at getElementsByClassName and querySelectorAll. Both have support in most new browsers.
The pure-JavaScript version isn't all that complicated:
var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++) {
if (elements.className.split(/\s+/).indexOf('red') !== -1) {
elements[i].style.color = 'red';
}
}
And for modern browsers:
var elements = document.querySelectorAll('a.red');
[].slice.call(elements).forEach(function(elem) {
elem.style.color = 'red';
});
Update: I still recommend using jQuery, but, if you want to learn how to do it without, I would recommend heading over to this site. This shows how to change link colors when you mouse over the link, but you can easily extrapolate for your specific situation: Javascript Change Link Text Color onmouseover
--
Ottomanlast has a good point about checking out jQuery to help you out with this task (although it can be done without the use of a library). However, just so you have an example of what he is talking about, here is how you could change link colors using jQuery.
$('.linkClass').click(function(){
$(this).css('color', 'green');
});
This example changes the color of a specific link when it is clicked.
$('a').css('color', 'green');
This example will change all the links to a green color.
$('.linkClass').click(function(){
$(this).removeClass('oldClass');
$(this).addClass('newClass');
});
This does the same thing as the first example, but this removes and adds CSS classes that you already have defined elsewhere. (I would recommend this method over just editing the CSS directly.)
Anyway, the point I'm trying to make is that jQuery makes it extremely easy to select and then make changes to the objects within your HTML document. You may want to take a look into it.
You can use document.getElementsByTagName("a"). This function returns an array of the <a> elements in the page. Loop over this array, and use .style.color = "#000000" in each element.
This is how I change all hyperlink colors (normal/hover):
function changeTextHyperlinkColours(inputColorNormal, inputColorHover) {
var sheets = document.styleSheets;
var slen = sheets.length;
for(var i=0; i<slen; i++) {
var rules = document.styleSheets[i].cssRules;
var rlen = rules.length;
for(var j=0; j<rlen; j++) {
if (rules[j].selectorText == 'a') {
rules[j].style['color'] = inputColorNormal;
}
if (rules[j].selectorText == 'a:hover') {
rules[j].style['color'] = inputColorHover;}
}
}
}
}
Also you can embed the link text in the span and change the color
<a href='www.mydomain.com'><span onclick='this.style.color="red"'>Visit Us</span></a>

Categories