Change CSS Property through JavaScript. (Uses ID's and Classes) - javascript

I'm trying to resize a panel using JavaScript to fit a small image into a panel, and struggling badly.
It's within the bold:
<body id="visCinemaTransRefund"><br>
<div id="content"><br>
<ul class="PayPanel" id="paymentDetails"><br>
Here's the CSS that needs modifying:
visCinemaTransRefund .PayPanel { width: 435px; }
How would I be able to modify with width of this panel?
I've also got a form I'm trying to resize within CSS:
visCinemaTransRefund FORM (width: 1005px;)

document.getElementById('paymentDetails').style.width = '1000px';

Have you tried using:
document.getElementById("paymentDetails").getElementsByClassName("PayPanel")[0].style.width="1000px"
Remember: getElementsByClassName return an array of elements, so using [0] you are indexing first element (and, of course, the only one).
Since getElementsById return a single elements, getElementsByClassName could be useless.

If you want to do this using CSS class :
HTML:
<div id="myDiv" class="medium"></div>
<button id="btn">Click me</button>
CSS:
#myDiv {
background-color: gray;
}
.medium {
height: 50px;
width: 50px;
}
.big {
height: 100px;
width: 100px;
}
JS:
document.getElementById("btn").onclick = function() {
var element = document.getElementById("myDiv"); // or document.getElementsByClassName("className")
if (element.className == "medium") {
document.getElementById("myDiv").className = "big";
} else {
document.getElementById("myDiv").className = "medium";
}
};
JSFIDDLE

Use the following code to change the width of tags by accessing HTML element from the DOM using getElement functions and setting width to it using setAttribute javaScript function.
document.getElementById("paymentDetails").setAttribute("style","width:500px;");
document.getElementById("visCinemaTransRefund").getElementsByTagName("form")[0].setAttribute("style","width:1000px;");

Using JavaScript:
document.getElementById('paymentDetails').style.width = '1000px';
Using JQuery:
$("paymentDetails").width(1000);
$("paymentDetails").css("width","1000px");

Related

How do I dim other elements in the webpage when I click on that element?

I am building a wordpress website and in the header part there is a search bar. How to create a dim effect(background:rgba(0,0,0,0.3)) on other elements except in search bar when I use the search bar (for example like in Quora.com). Also this code(your answer) should be working if I use code for other elements(other than search bar) like input box,or any other div.
I will be more satisfied if you come with an answer that is flexible to use for any div.
Thanking you in advance.
You need to add a click event to the element that needs to be clicked. You can then bind a function to that event that is triggered upon the click, as follows:
var test = document.getElementById("test");
test.addEventListener("click", changeColour);
function changeColour() {
var changeme = document.getElementById("change");
changeme.classList.add("addopacity");
}
#change {
background: #000;
width: 100px;
height: 100px;
}
#change.addopacity {
opacity: 0.2;
}
<button id="test">Click me please</button>
<div id="change"></div>
Please note, you don't have to add a class to the target element like I have above, you can just as easily add an inline style with changeme.style.opacity = "0.2"; within the function.
If you want to click on the element itself and have it change colour, you can do something similar:
var test = document.getElementById("change");
test.addEventListener("click", changeColour);
function changeColour() {
this.classList.add("addopacity");
}
#change {
background: #000;
width: 100px;
height: 100px;
color: #fff;
}
#change.addopacity {
opacity: 0.2;
}
<div id="change">CLICK ME</div>
Use the opacity property and apply it wherever you need it.
div {
opacity: 0.3;
}

JQuery: create corresponding elements with same custom attrs

Fiddle here: http://jsfiddle.net/yv1vLhd9/
For whatever reasons, suppose I want to replace three dom elements with three others using JQuery, but I want to transfer one or more data attributes from the first elements onto their corresponding replacements.
Given the following HTML:
<div class='original' data-custom="dog"></div>
<div class='original' data-custom="cat"></div>
<div class='original' data-custom="sheep"></div>
And the following CSS:
div {
width: 100px;
height: 100px;
}
div:before {
content: attr(data-custom);
}
.original {
border: blue solid 1px;
}
.new {
border: pink solid 1px;
}
How can I make sure there is a new element with each of the custom data attributes?
For example:
$(document).ready( function(){
var $originalEl = $('.original')
var originalData = $originalEl.data('custom')
var replacement = '<div class="new" data-custom="' + originalData + '"></div>'
$originalEl.after(replacement).hide()
});
But this creates three new data-custom="dog" attributes.
You must use $.each for the element.
Starting after you declare $originalEl
$originalEl.each(function(){
// code here
})
Here is your code updated http://jsfiddle.net/yv1vLhd9/4/
http://jsfiddle.net/VixedS/wz95hh3r/1/
$(document).ready(function(){
$('.original').each(function(){
$(this).hide().clone().attr('class','new').show().appendTo('body');
})
});
jQuery provides a host of DOM manipulation methods that will help you achieve the desired input. As noted by some of the other answers, you'll need to traverse over the set of matched elements using $.each. In addition, rather than creating new elements from strings, you can use the .clone() method to:
clone the existing element
modify your new element
insert it after the original element
traverse to the original element
and finally hide the original element.
$(function () {
$('.original').each(function (idx, elem) {
$(elem)
.clone()
.removeClass('original')
.addClass('new')
.insertAfter($(elem))
.prev()
.hide();
});
});
div {
width: 100px;
height: 100px;
}
div:before {
content: attr(data-custom);
}
.original {
border: blue solid 1px;
}
.new {
border: pink solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='original' data-custom="dog"></div>
<div class='original' data-custom="cat"></div>
<div class='original' data-custom="sheep"></div>
API Method References:
jQuery.each()
.clone()
.removeClass()
.addClass()
.insertAfter()
.prev()
.hide()

set a newly created div on top of the older divs

I have a bunch of divs inside a container. The position of the content divs is relative, because I want them to appear one below the other and their height is unknown.
These divs are created dynamically (appendchild) inside the container div. Now, each div appears on the end (bottom) of the stack but my requirement is that the divs have a "newest first" option too, that is, each new div appears on top, not on bottom of the content divs (if the user selects the "newest first" in the settings).
html:
<div class="container">
<div id="div1" class="content">aaa<br>aaa</div>
<div id="div2" class="content">bbb<br><br>bbb</div>
<div id="div3" class="content">ccc</div>
<div id="div4" class="content">ddd</div>
</div>
css:
.container {
position: absolute;
top: 10px;
left: 10px;
right: 10px;
bottom: 10px;
border: 1px solid red;
}
.content {
position: relative;
top: 0px;
left: 5px;
width: 200px;
height: auto;
border: 1px solid blue;
margin: 3px;
}
http://jsfiddle.net/jk559/1/
so I'd like the end-user visible order to be: div4, div3, div2, div1.
How can I achieve this? (css/js)
preferrably no jquery.
thanks in advice!
Pure css solution:
Use flexbox to achieve this.
.container {
display:flex;
flex-direction:column-reverse;
justify-content: flex-end;
align-content: flex-end;
}
Updated fiddle here.
Read more information here.
try this
theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.setAttribute("id","div5");
theKid.setAttribute("class","content");
theKid.innerHTML = 'eee';
// append theKid to the end of theParent
theParent.appendChild(theKid);
// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);
Demo Fiddle http://jsfiddle.net/jk559/4/
You can easily do it with JQuery with the following function.
$('.container > div').each(function() {
$(this).prependTo(this.parentNode);
});
UPDATED FIDDLE
As you mentioned in the question, I will try to attain the expected output with the pure javascript.
You can insert content in the beginning simply using .prepend() .
$(".container").prepend("<div id='div5' class='content'>eee</div>");
Demo
JS FIDDLE UPDATED DEMO
Use prepend() to add as first child of an element
/* $( ".container" ).prepend( "Your div with id here" ); */
/* Example */
$( ".container" ).prepend( "<div id='div5' class='content' >div5 on top </div>" );
Take a look at this answer about reordering dom items.
Basically, you have to maintain a state that decides the ordering. When you insert items (see insertItem below) you append or prepend based on the state. When the user selects the newest first option (see newFirst below), you first reverse the dom elements and then flip the state so that subsequent insert happen at the right place.
var newFirst = false;
var list = document.getElementById('my-list');
function newFirst() {
var items = list.childNodes;
var itemsArr = [];
for (var i in items) {
if (items[i].nodeType == 1) { // get rid of the whitespace text nodes
itemsArr.push(items[i]);
}
}
itemsArr.reverse();
for (i = 0; i < itemsArr.length; ++i) {
list.appendChild(itemsArr[i]);
}
newFirst = !newFirst;
}
function insertItem(content) {
var item = document.createElement("div");
item.setAttribute("class","content");
item.innerHTML = content;
if(newFirst) {
list.insertBefore(item, list.firstChild);
} else {
list.appendChild(item);
}
}
try this :
$("div[id*=div]").sort(function(a,b){
if(a.id > b.id) {
return -1;
} else {
return 1;
}
}).each(function() {
var elem = $(this);
$(".container").append(elem);
});
this will sort your divs inside container like this : div4, div3, div2, div1
if you want change the order to : div1, div2, div3, div4 just change if(a.id > b.id) to if(a.id < b.id)
you can add a link called change order then call this code when you click on it

How to hide/show div tags using JavaScript?

Basically, I'm trying to make a link that, when pressed, will hide the current body div tag and show another one in its place, unfortunately, when I click the link, the first body div tag still appears. Here is the HTML code:
<div id="body">
<h1>Numbers</h1>
</div>
<div id="body1">
Body 1
</div>
Here is the CSS code:
#body {
height: 500px;
width: 100%;
margin: auto auto;
border: solid medium thick;
}
#body1 {
height: 500px;
width: 100%;
margin: auto auto;
border: solid medium thick;
display: hidden;
}
Here is the JavaScript code:
function changeDiv() {
document.getElementById('body').style.display = "hidden"; // hide body div tag
document.getElementById('body1').style.display = "block"; // show body1 div tag
document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; // display text if JavaScript worked
}
NB: CSS tags are declared in different files
Have you tried
document.getElementById('body').style.display = "none";
instead of
document.getElementById('body').style.display = "hidden";?
just use a jquery event listner , click event.
let the class of the link is lb... i am considering body as a div as you said...
$('.lb').click(function() {
$('#body1').show();
$('#body').hide();
});
Use the following code:
function hide {
document.getElementById('div').style.display = "none";
}
function show {
document.getElementById('div').style.display = "block";
}
You can Hide/Show Div using Js function. sample below
<script>
function showDivAttid(){
if(Your Condition)
{
document.getElementById("attid").style.display = 'inline';
}
else
{
document.getElementById("attid").style.display = 'none';
}
}
</script>
HTML -
Show/Hide this text
Set your HTML as
<div id="body" hidden="">
<h1>Numbers</h1>
</div>
<div id="body1" hidden="hidden">
Body 1
</div>
And now set the javascript as
function changeDiv()
{
document.getElementById('body').hidden = "hidden"; // hide body div tag
document.getElementById('body1').hidden = ""; // show body1 div tag
document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked";
// display text if JavaScript worked
}
Check, it works.
Consider using jQuery. Life is much easier with:
$('body').hide(); $('body1').show();
try yo write
document.getElementById('id').style.visibility="hidden";

How change content value of pseudo :before element by Javascript [duplicate]

This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
Closed 2 years ago.
I have the grap constructured by CSS, which is dynamically changes by JS. I show graph max value by pseudo element as:
.graph:before {
content:""; //value that want set by JS
position:absolute;
top:0;
left:0;
}
That's why I need to set this value by JS. I tried $(".graph:before").css("content", hh); but it didn't help. How to get that value?
I hope the below snippet might help, you can specify the content value you want via JS using the CSS attr() function.
Below you have two options: to use JavaScript or jQuery:
jQuery:
$('.graph').on('click', function () {
//do something with the callback
$(this).attr('data-before','anything'); //anything is the 'content' value
});
JavaScript:
var graphElem = document.querySelector('.graph');
graphElem.addEventListener('click', function (event) {
event.target.setAttribute('data-before', 'anything');
});
CSS:
.graph:before {
content: attr(data-before); /* value that that refers to CSS 'content' */
position:absolute;
top: 0;
left: 0;
}
Update (2018): as has been noted in the comments, you now can do this.
You can't modify pseudo elements through JavaScript since they are not part of the DOM. Your best bet is to define another class in your CSS with the styles you require and then add that to the element. Since that doesn't seem to be possible from your question, perhaps you need to look at using a real DOM element instead of a pseudo one.
You can use CSS variable
:root {
--h: 100px;
}
.elem:after {
top: var(--h);
}
let y = 10;
document.documentElement.style.setProperty('--h', y + 'px')
https://codepen.io/Gorbulin/pen/odVQVL
I believe there is a simple solution using the attr() function to specify the content of the pseudo element. Here is a working example using the 'title' attribute, but it should work also with custom attributes.:
document.getElementById('btn_change1').addEventListener("click", function(){
document.getElementById('test_div').title='Status 1';
});
document.getElementById('btn_change2').addEventListener("click", function(){
document.getElementById('test_div').title='Status 2';
});
#test_div {
margin: 4em;
padding:2em;
background: blue;
color: yellow;
}
#test_div:after {
content:attr(title);
background: red;
padding:1em;
}
<button id='btn_change1'>Change div:after to [Status 1]</button>
<button id='btn_change2'>Change div:after to [Status 2]</button>
<div id='test_div' title='Initial Status'>The element to modify</div>
People who are still looking some solution of same problem, it is doable as follows using jQuery:
<button id="changeBefore">Change</button>
<script>
var newValue = '22';//coming from somewhere
var add = '<style>.graph:before{content:"'+newValue+'"!important;}</style>';
$('#changeBefore').click(function(){
$('body').append(add);
});
</script>
This example illustrate that on clicking button: changeBefore , the value for .graph:before will change as per new dynamic coming value for it.
For more description about changing of :before or :after element style or getting its content:
Lets suppose your HTML is like this:
<div id="something">Test</div>
And then you are setting its :before in CSS and designing it like:
#something:before{
content:"1st";
font-size:20px;
color:red;
}
#something{
content:'1st';
}
Please notice I also set content attribute in element itself so that you can take it out easily later.
Now there is a button clicking on which, you want to change the color of :before to green and its font-size to 30px. You can achieve that as follows:
Define a css with your required style on some class .activeS :
.activeS:before{
color:green !important;
font-size:30px !important;
}
Now you can change :before style by adding the class to your :before element as follows:
<button id="changeBefore">Change</button>
<script>
$('#changeBefore').click(function(){
$('#something').addClass('activeS');
});
</script>
If you just want to get content of :before, it can be done as:
<button id="getContent">Get Content</button>
<script>
$('#getContent').click(function(){
console.log($('#something').css('content'));//will print '1st'
});
</script>
I hope it helps
I had a similar problem, but with icons. I needed to switch the play and pause icons for an audio player in html5.
The problem here was that HTML, CSS and jQuery all interpret differently the "content" values to show icons, due to the use of \ symbol.
So the best workaround is to delete and re-create the node. Here's my code:
<ul class="list list--buttons">
<li><i class="fa fa-step-backward"></i></li>
<li><i class="fa fa-play"></i></li>
<li><i class="fa fa-step-forward"></i></li>
</ul>
And the script
<script type="text/javascript">
$(
function(){
var aud = $('audio')[0];
$('.playpause').on('click', function(e){
e.preventDefault();
if (aud.paused) {
aud.play();
/* from play icon to pause icon */
$('.playpause .fa-play').remove();
$('.playpause').append('<i class="fa fa-pause"></i>');
}
else {
aud.pause();
/* from play icon to pause icon */
$('.playpause .fa-pause').remove();
$('.playpause').append('<i class="fa fa-play"></i>');
}
})
$('.next').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
$('.previuos').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
aud.ontimeupdate = function(){
$('.progress').css('width', aud.currentTime / aud.duration * 100 + '%')
}
})
</script>
Hope it helps!
You can use document.styleSheets to modify pseudo selector cssRules
document.styleSheets[0].cssRules[0].style.content = '"111"';
If you use something like an onoffswitch and want to translate the css content attribute with i18next then you can use one of the i18next Framework example from github (i18next Jquery Framework) and then you extended the function with this code:
var before = i18next.t('onoffswitch.before');
var after = i18next.t('onoffswitch.after');
$('.onoffswitch-inner')
.attr('data-before', before )
.attr('data-after', after );
and the css code must be this:
.onoffswitch-inner:before {
content: attr(data-before);
padding-left: 10px;
background-color: #65AFF5; color: #FFFFFF;
}
.onoffswitch-inner:after {
content: attr(data-after);
padding-right: 10px;
background-color: #EEEEEE; color: #999999;
text-align: right;
}

Categories

Resources