I am working on making a number list with each number on its individual div. So far I am able to remove the div with Javascript (on click), but I would like to enable JQuery so that I am able to add a class to a div and then remove all divs of that class with a button or something like that.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=203">
<title>Lista Mundial</title>
<style>
.divContainer {
width: 35px;
height: 25px;
border: solid 1px #c0c0c0;
background-color: #e1e1e1;
font-family: verdana;
float: left;
}
.text {
font-size: 15px;
font-family: verdana;
color: black;
margin-top: 4px;
}
h4 {
font-family: Verdana;
color: black;
text-decoration: none;
}
</style>
</head>
<body>
<h4>Double click para borrar un numero</h4>
<script type="text/javascript">
for(var i = 1; i <= 639; i++){
var divTag = document.createElement("div");
divTag.id = i;
divTag.className = "divContainer";
document.body.appendChild(divTag);
divTag.ondblclick = function(){this.parentNode.removeChild(this)};
var pTg = document.createElement("p");
pTg.setAttribute("align", "center");
pTg.className = "text";
pTg.innerHTML = (i);
document.getElementById(i).appendChild(pTg);
}
</script>
</body>
</html>
http://jsfiddle.net/ramonfabrega/AZSy8/
For simplicity, I just tried hiding the div's clicked, but JQuery does not seem to work. So something must be off.
Two issues:
1) jQuery wasn't loaded.
2) You were trying to bind the click event on an invalid selector (divTag instead of div)
Here's an updated fiddle: http://jsfiddle.net/LFC3A/2/
Regarding #2 - jQuery allows you to select an element multiple ways. The most common is to use a selector. The majority of selectors jQuery supports are from CSS 1 - 3, though jQuery supports some of its own custom selectors (such as div:eq, div:gt, and so on...) Check out the selectors page here: http://api.jquery.com/category/selectors/
Now, if your markup was:
<body>
<divTag>My Custom Div Tag</divTag>
<div>My regular DIV</div>
</body>
Then your original fiddle would have worked. In fact, here's an updated fiddle demonstrating that: http://jsfiddle.net/FpMAw/ (I updated your createElement to return a custom element, divTag)
The other way of accessing jQuery is by passing it a DOM element. Something like:
var $body = $(document.body) is equivalent to var $body = $('body')
If you reference that, you now have a jQuery object with a bunch of useful helper methods. So, in our previous example, we can now do:
$body.css('color', 'red')
Hopefully this helps explain a bit more why it didn't work. If you have any other questions, feel free to ask :)
Fiddle Demo
you are not including jQuery library in the fiddle
change $('divTag') to $('div')
Read $( "element" )
$(document).ready(function () {
$('div').click(function () {
$(this).hide();
});
});
Start Learning
jQuery API Documentation
This will create and add a click handler at the same time.
$('<div>').click(function(e){ this.addClass('active');})
Related
I am working on a project and I am having difficulty writing out the code I need to make the ball in my project change to the same color as the button in the top left hand corner when I change the color. I need them to be in sync. A few things to keep in mind this is without jquery pure vanilla javascript and ecma 5
With that being said here are the instructions for the project:
Use Javascript form events to adjust the background colour of a circle on the screen.
Fork this repository.
**Make a <form> tag with an <input> inside it—use type="color" for the input.
When the form’s change event fires, adjust the background-color of the ball to match the input’s value.
Run it through Markbot and make sure it passes all the checks.
Here is what my project currently looks like:
When I click on the button in the top left hand corner this pops up:
Here is my html:
<!DOCTYPE html>
<html>
<head>
<title>CircleColourr</title>
<link href="main.css" rel="stylesheet">
</head>
<body>
<div class="ball"></div>
</body>
<script src="jquery.min.js"></script>
<script src="main.js"></script>
</html>
Here is my main.css
html{
box-sizing: border-box;
}
*, *::before, *::after{
box-sizing: inherit;
}
.ball{
width: 200px;
height: 200px;
position: absolute;
top: 200px;
left: 200px;
background-color: ;
border-radius: 100px;
}
Here is my main.js
var body = document.querySelector('body');
var h2 = document.createElement('h3');
var forma = document.createElement('form');
var inForma = document.createElement('input');
var h2 = document.createTextNode('Colour');
inForma.type = 'color';
inForma.id = 'listen';
body.appendChild(h2);
forma.appendChild(inForma);
body.appendChild(forma);
var bally = document.querySelector('.ball');
bally.style.backgroundColor = forma; // first attempt
console.log(bally.style.backgroundColor = forma);//first attempt
var button = document.getElementById('listen').addEventListener ('click', change);
function change(e){
document.querySelector('.ball').style.backgroundColor = forma;
}
I have made two attempts the first one just assigns the actual form element to the ball div and the second one nothing appears to be happening. The thought process for me was to assign the forma to the backgroundColor of the ball. I just need some guidance please.
there's a couple issues I see
there's a space here, which will break it
getElementsById is not a valid function, use getElementById
the event listener click will fire when you open the ui, you want to use a change listener, to update value after the user selects color
var button = document.getElementsById('listen').addEventListener ('click', change);
you don't have an element with a class called class, you do have .ball though
document.querySelector('.class').style.backgroundColor
here's a working version
https://jsfiddle.net/rp9kxLyu/
I need to change dynamically my css properties. I know that the right way to do it is with: document.getElementById("XXXX").style.fontSize = "xx-large";
However, when I have this css:
#year1 .subdomain-text {
fill: #000;
font-size: 6px;
}
I haven't been able to find the way to access it, and I have tried any possible permutation (nothing works!):
document.getElementById("year1.subdomain-text").style.fontSize = "xx-large";
document.getElementById("year1").style.fontSize = "xx-large";
document.getElementById("subdomain-text").style.fontSize = "xx-large";
document.getElementById("#year1.subdomain-text").style.fontSize = "xx-large";
....
Any idea how to make it happen?
Thanks!
You are using .getElemenByID() which means you specify just the ID name no need to include the class name i.e. document.getElementById("year1").style.fontSize = "xx-large";
Example here :http://jsfiddle.net/Nb7wy/1770/
document.getElementById retrieves html element by its id attribute. In your case, it should be:
document.getElementById("year1")
If the id is unique, as expected, the class is not necessary for the selector in the css rule either. You could just remove the class from your css rule.
For other cases where combining selectors is needed, it can be used document.querySelector(css_selector) (instead of document.getElementById).
Working code:
<html>
<head>
<style>
#year1 .subdomain-text {
fill: #000;
font-size: 6px;
}
</style>
</head>
<body>
<p id="year1" class="subdomain-text">Texto prueba</p>
<input type="button" onclick="test();" />
<script>
function test() {
document.getElementById("year1").style.fontSize = "xx-large";
}
</script>
</body>
</html>
I have a simple html (see here: http://plnkr.co/edit/nqfLNfYxV2B8AwsDAcNu?p=preview):
<section class="divs">
<div>div1
<div>div1.1.
<div>div1.1.1</div>
<div>div1.1.2</div>
</div>
<div>div1.2.</div>
</div>
<div>div2</div>
</section>
I want go through all section div:first-child elements and add some mark to see if it belongs to that selector. In order to implement this there is following code:
$(function(){
$('section div:first-child').each(function(index,element){
console.log('element.html before: '+$(element).html());
var elementHTML = '['+index+']: '+$(element).html();
$(element).html(elementHTML);
console.log('element.html after: '+$(element).html());
});
});
But it adds the [index] to the element's html only for the first selector.
Can anybody explain why?
UPD
Not quite the answer, but nevertheless, Pete gave me the understanding of the problem.
So in order to make it working there is necessary to change
$(element).html(elementHTML);
to
$('section div:first-child')
.eq(index).html(elementHTML);
It's not about efficiency ofcourse, it's about how to solve the problem in place. The real solution, no doubt, is to use .prepend() method.
Your problem is the first time instance of section div:first-child is the top level div (div1) so when you replace the html of this div, the divs 2 and 3 in the loop no longer exist in the dom and so they don't get updated as such
Instead of replacing the html, just prepend the text:
$('section div:first-child').each(function(index, element) {
$(element).prepend('[' + index + ']: ');
});
New plunker
$('section div:first-child')
https://developer.mozilla.org/en-US/docs/Web/CSS/%3Afirst-child
The :first-child CSS pseudo-class represents any element that is the
first child element of its parent.
If you want to select only the divs one level below section, you can try:
$('section > div')
Since you replace the HTML every time, the elements are replaced on the fly. To avoid that, don't replace the entire HTML, just $.prepend() to it. Try it:
$(function() {
$('section div:first-child').each(function(index, element) {
console.log('element.html before: ' + $(element).html());
var elementHTML = '[' + index + ']: ';
$(element).prepend(elementHTML); // <------------------------ HERE !
console.log('element.html after: ' + $(element).html());
});
});
body * { box-sizing: border-box; }
div { background-color: white; }
section div { border: solid 2px #888; margin: 4px; padding: 10px; }
section div:first-child { background-color: lightcyan; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<section class="divs">
<div>div1
<div>div1.1.
<div>div1.1.1</div>
<div>div1.1.2</div>
</div>
<div>div1.2.</div>
</div>
<div>div2</div>
</section>
When you set the html, the elements below it don't get updated, they get replaced
Your code works, it's just updating the elements that are no longer attached to the DOM.
I have a progressbar on my website and this is a part of its css:
.progress-bar span {
display: inline-block;
height: 25px;
width: 78%; //the actual position
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
border-radius: 3px;
//other css
}
I have to change the width that indicates the position of the progression (the line you see here). This is the first time I use progress bars and I have no idea about how to setup the javascript code.
Any advice? jsfiddle
Here is the way without jQuery
HTML
<div class="progress-bar" align="left">
<span id="prog"></span>
</div>
JS:
var elem = document.getElementById("prog");
elem.style.width = "88%";
I'd recommend using jQuery to make your javascript calls much simpler. You can download the latest version here: http://jquery.com/download/
First, include the jQuery file in the head of your html like this:
<head>
...
<script type="text/javascript" src="<location of file>jquery-1.10.2.min.js"></script>
...
</head>
Then within your own javascript code, you can move the position of the progress bar like so:
jQuery('.progress-bar scan').css('width', <desired width>);
Hopefully that helps.
You can use:
document.querySelectorAll('.progress-bar span').forEach(function(elem) {
elem.style.width = '<YOUR WIDTH>';
});
no jQuery
I just incremented the width this way:
function increment(){
var width = document.getElementById('progressbar').clientWidth;
var divArray = document.getElementById('progressbar');
if(width<500){
var largura = width+10;
divArray.style.width = largura+'%';
setTimeout("increment()",1000);
}
else{
window.location.href = "http://www.google.com/";
}
}
And does it every second so it will be incremented every second but u can change it the way you want.
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;
}