Hide DIV depending on text inside another DIV in DOM with javascript? - javascript

I need to hide a DIV depending on userroles. I have no variable to use from these userroles, except text inside a title tag.
html:
<title>admin</title>
If admin then hide the DIV for an example
<div class="demo"></div>.
I can only use Vanilla Javascript.
Update: This hides the div, but shows it for a blink at pageload:
$('document').ready(
function() {
function _title(){
if(document.title=="admin"){
document.getElementById('demo').style.display="none";
}
}
window.onload=_title;
});

Okay well this should answer your question.
This will set style none for element with the ID of demo.
function _title(){
if(document.title=="admin"||document.title=="admin1"){
document.getElementById('demo').style.display="block";
}
}
window.onload=_title;
If you to use class rather than id to allow this function to work with multiple elements....
function _title(){
if(document.title=="admin"){
var DemoClass = document.getElementsByClassName('demo');
for(var i=0; i<DemoClass.length; i++) {
DemoClass[i].style.display="block";
}
}
}
window.onload=_title;
If this answers your question, marking your question as answered would be appreciated.
Simple add this to your page
For id
<style type="text/css">
#demo{display:none;}
</style>
For class
<style type="text/css">
.demo{display:none;}
</style>
---- Titles that contain the word Admin ----
For Class
function _title(){
var allow = document.title.search("admin");
if(allow>-1){
//Set display for demo element
var DemoClass = document.getElementsByClassName('demo');
for(var i=0; i<DemoClass.length; i++) {
DemoClass[i].style.display="block";
}
}}
For id
function _title(){
var allow = document.title.search("admin");
if(allow>-1){
//Set display for demo element
document.getElementById('demo').style.display="block";
}}

Related

JavaScript/CSS Show respective div on click from grid

I have a working grid that show a cell for every title in the json:
async function loop_iteration(json, i, arr) {
arr.push(`<a onClick="show()" class="cell" id=${i}"><div >${json[i].title}</div> </a>`)
arr.push(`<div class="info" id=${i}>${json[i].title}<br><br><br><br><br>Game Size: ${json[i].size}<br><br>Last Update: ${json[i].date}</div>`)
}
I want to show on click of the class info.
The problem is that it gives always the same title(first), it's like is always the first cell to be clicked
I show the info div like this:
<script>
function showinfo() {
var node = document.querySelector('.cell.info')
var visibility = node.style.visibility;
node.style.visibility = visibility == "visible" ? 'hidden' : "visible"
}
</script>
while if i show the div using this:
function show(){
var divsToHide = document.getElementsByClassName("info");
for(var i = 0; i < divsToHide.length; i++)
{
divsToHide[i].style.visibility="visible";
}
//document.getElementsByClassName('info')['${i}'].style.visibility = 'visible';
}
happen something strange, the div showed is not the first but is like it show all the div
Thanks for any help.
I find out the problem.
It was the javascript, so i extract the id and then iterate the class with the id
function show(clicked_id){
clicked_id = parseFloat(clicked_id);
document.getElementsByClassName('info')[clicked_id].style.visibility = 'visible';
}

CSS selector for ALL elements with SAME CLASS after and before current element

I was looking here: CSS Selector for selecting an element that comes BEFORE another element?
...but wasn't able to find a correct answer for my issue.
Here is a fiddle example: https://jsfiddle.net/Munja/bm576q6j/3/
.test:hover, .test:hover + .test
With this, when I :hover element with .test class, I achieved to change style for current element with .test class and first next element with .test class.
What am I trying to achieve?
When I select any row/column (e.g agent 2), I want to apply same style for ALL elements with that same class (.test in this case).
If it is not possible to achieve this with css only, * I am willing to accept and other good solution.*
Thank you.
In your specific case you can use
tbody:hover > .test {
background: green;
}
fiddle: https://jsfiddle.net/bm576q6j/4/
Note that if you add more classes in the same tbody it will not give what you want. Check also this question: Hover on element and highlight all elements with the same class
So, after waiting for several more hours, I have decided to use JavaScript solution mentioned in answer from #BasvanStein. Posting it here as answer, to make things easier for someone else with same issue.
Here is a working fiddle: https://jsfiddle.net/Munja/bm576q6j/15/
var elms = document.getElementsByClassName("test");
var n = elms.length;
function changeColor(color) {
for(var i = 0; i < n; i ++) {
elms[i].style.backgroundColor = color;
}
}
for(var i = 0; i < n; i ++) {
elms[i].onmouseover = function() {
changeColor("red");
};
elms[i].onmouseout = function() {
changeColor("white");
};
}

How to add a new rule to an existing CSS class

In the code below i have illustrated what I am trying to achieve...
Altering an existing CSS class by adding a new rule to it.
<head>
<style>
h4.icontitle
{font-size: 22pt;}
</style>
</head>
<body>
<script type="text/javascript">
textpercent = 84;
document.styleSheets[1].cssRules.['h4.icontitle'].style.setProperty('-webkit-text-size-adjust', textpercent+'%', null);
</script>
<h4> hello </h4>
</body>
This is for a pre-process element of a site running on screens of different sizes.
The result will be...
h4.icontitle
{font-size: 22pt;
-webkit-text-size-adjust:84%;}
Which will be visible when inspecting the DOM.
Any ideas would be most welcome. Javascript only - no JQuery here...
SOLVED.
After a lot of trial and error, here is a working function that allows javascript to insert styles directly into the CSS
function changeCSS(typeAndClass, newRule, newValue)
{
var thisCSS=document.styleSheets[0]
var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules
for (i=0; i<ruleSearch.length; i++)
{
if(ruleSearch[i].selectorText==typeAndClass)
{
var target=ruleSearch[i]
break;
}
}
target.style[newRule] = newValue;
}
Called with
changeCSS("h4.icontitle","backgroundColor", "green");
Hopefully others will find this a useful method to use variables within their CSS in pure javascript.
This function works perfectly for my site.
function changeCSS(typeAndClass, newRule, newValue)
{
var thisCSS=document.styleSheets[0]
var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules
for (i=0; i<ruleSearch.length; i++)
{
if(ruleSearch[i].selectorText==typeAndClass)
{
var target=ruleSearch[i]
break;
}
}
target.style[newRule] = newValue;
}
Called with
changeCSS("h4.icontitle","backgroundColor", "green");
/**
Use this to update style tag contents
**/
var css = 'h1 { background: grey; }',
head = document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
To work with elements within body use querySelector to target elements upon their CSS identifier. This should help you
https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
var el = document.querySelector(".icontitle");
el.setAttribute("style","-webkit-text-size-adjust:84%");
Or you can prepare a css snippet and use it conditionally ex: if "new_css" is the new change then
/**css code in style tag**/
.icontitle{
/**style at initial stage**/
}
.icontitle-new-modified{
/**modified css style at later stage**/
}
//after a condition is satisfied
el.setAttribute("class","icontitle-new-modified");
I put an example together that should suit your needs
DEMO jsFiddle
// this gets all h4 tags
var myList = document.getElementsByTagName("h4"); // get all p elements
// this loops through them until it finds one with the class 'icontitle' then it assigns the style to it
var i = 0;
while(i < myList.length) {
if(myList[i].className == "icontitle") {
myList[i].style.color="red";
}
i++;
}
Try this piece of code
$('h4.icontitle').css('-webkit-text-size-adjust','84%');

Create my own Radio-like-button with a DIV?

I'm trying to make a site where users can create there own social networking buttons. (I know its been done but its mostly for practice). A part of the site will allow users to choose the shape of the buttons. Here is the HTML:
<div class="design" id="shape">
<div class="shapeSelect square" id="square"></div>
<div class="shapeSelect rounded" id="rounded"></div>
<div class="shapeSelect circle" id="circle"></div>
</div>
What I would like to do is add an event listener when the div is clicked. After it's clicked the class attribute would be changed to "selected." When another one would be click then the first clicked one would be cleared and the next one would be selected. Just like with radio buttons.
I am familiar with JavaScript and my idea was this:
window.onload = function () {
'use strict';
document.getElementById("square").addEventListener('click', function (e) {//adds the event listener
divArray = document.getElementById("shape");//Here is my first issue: an array is not returned
if (!(document.getElementById("square").getAttribute("class") == "shapeSelect square selected")) {// checks to make sure its not already selected
for (i = 0, count = document.getElementById("shape").length; i < count; i++) {// if it isn't go through the array
divArray[i]// and this is where i also get stuck. I Can't figure out how i would return the class attribute to be class="shapeSelect circle" instead of class="shapeSelect circle selected"
};
}
}, false);
}
A more simple version of scdavis41's answer:
$(document).ready(function(){
$('#shape > .shapeSelect').click(function(){
$('#shape > .shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
I also put a selector that includes the control's main div id in case you want to put this control more then once in your page.
** EDIT **
If you absolutly want to use javascript and DOM try this:
document.getElementById("square").addEventListener('click', function (e) {
var divArray = document.getElementById("shape").getElementsByTagName("div"); //Get all the div child element of the main div
for (i = 0, count = divArray.length; i < count; i++) {
if(divArray[i].getAttribute("class").indexOf("selected") !== -1) { //check if the selected class is contained in the attribute
divArray[i].setAttribute("class", divArray[i].getAttribute("class").replace("selected", "")); // clear the selected class from the attribute
}
};
document.getElementById("square").setAttribute("class", document.getElementById("square").getAttribute("class").concat(" selected")); //select the square
}, false);
This is verbose, but you could use:
$(document).ready(function(){
$('#square').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
$('#circle').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
$('#rounded').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
This is jQuery, which means you have to load the jQuery library, but putting this above your script tag:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
If you are looking for a pure JavaScript solution, you could try this:
if(option == 'add'){
element.className = element.className + ' selected';
element.onclick = function() {select(this.id, 'remove')};
element.innerHTML = '✓';
}
else if(option == 'remove'){
element.className = element.className.replace(/\bselected\b/,'');
element.onclick = function() {select(this.id, 'add')};
element.innerHTML = '';
}
JSFiddle: http://jsfiddle.net/hKePD/
**EDIT**
Or if you were looking for a checkbox to be always checked, you could try this: http://jsfiddle.net/hKePD/1/
Building on scadvis41's answer, this is much shorter:
$(document).ready(function(){
$('.shapeSelect').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});

Javascript change element properties onmouseover onmouseout

I've got this code:
<script type="text/javascript">
$(document).ready(function () {
$('.thumbspiccolimabelli').hover( function(e){
var ider = $(this).attr('title'); // e.g. the other element I want to change colour on
console.log(ider);
var test = document.getElementsByClassName(ider);
for(var i = 0; i < test.length; i++) {
if(test[i].style.color = 'red'){
test[i].style.color = 'white';
}
else{
test[i].style.color = 'red';
}
}
console.log(test);
});
});
</script>
And i'm trying to change the colour of all element on the page that have the id of the element i'm hovering over, but it does'nt quite work.
The element im hovering over has a ID of "myhoverelement" and I have span elements that share the same ID, these ones I want the colour to change on.
Thanks
You dont need javascript for this
CSS:
.thumbspiccolimabelli {
background-color: none;
}
.thumbspiccolimabelli:hover {
background-color: #fff;
}
Is this what you want?
'#myhoverelement' is being replaced with '.myhoverelement'. IDs must be unique.
$('.thumbspiccolimabelli').on('hover' , function() {
$('.myhoverelement').each(function() {
$(this).css('background' , '#ffffff');
});
});

Categories