I'm trying to create some draggable boxes in javascript. I decided to make an empty class "draggable" in CSS and a "box" class. The code is as follows:
<!DOCTYPE html>
<html>
<head>
<style>
.draggable
{
}
.box
{
position: absolute;
width: 80px; height: 60px;
padding-top: 10px;
text-align: center;
font-size: 40px;
background-color: #222;
color: #CCC;
}
</style>
</head>
<body>
<div class="draggable box">1</div>
<div class="draggable box">2</div>
<div class="draggable box">3</div>
<script>
var draggableStuff = document.querySelectorAll('draggable');
var tabLength = draggableStuff.length;
alert(tabLength);
</script>
</body>
The problem is that tabLength is always zero. I want to get an array filled with all draggable stuff. I'm new to javascript. What have I missed here?
You want to select elements by class, so don't forget about the dot:
var draggableStuff = document.querySelectorAll('.draggable');
Another option is to use document.getElementsByClassName:
var draggableStuff = document.getElementsByClassName('draggable');
I came across this situation. Although it is too old post I would like to help people with my answer:
To select all the elements (no matter what it is, it may be div, span, h1, etc...) with particular attribute
Without value?:
var dragables = document.querySelectorAll('[draggable]');
With value?:
var dragables = document.querySelectorAll('[draggable="true"]');
Related
I have recently started learning DOM and I have seen some examples of it, however, I'm trying to make a function (getting id) which would trigger after being double clicked.
This is the CSS, HTML and JavaScript codes I'm using.
function getID() {
var x = document.getElementsByClassName("blueblock")[0].id;
document.getElementById("xx").innerHTML = x;
.blueblock {
width: 30%;
height: 50vh;
float: left;
background-color: lightblue;
text-align: justify;
overflow: auto;
}
<p id="xx" ondblclick="getID()">
<div class="blueblock" id="bluebl">
<p>Just some text inside of the block.</p>
</div>
How should I change my code so that clicking on any part of the blueblock would trigger the function and output the id value?
This happens because the <p> tag you have does not have a content. If you would add text to the <p> and double click the text it will work.
The solution for this is to use div instead of p:
function getID() {
var x = document.getElementsByClassName("blueblock")[0].id;
document.getElementById("xx").innerText = x;
}
.blueblock {
width: 30%;
height: 50vh;
float: left;
background-color: lightblue;
text-align: justify;
overflow: auto;
}
<div id="xx" ondblclick="getID()">
<div class="blueblock" id="bluebl">
<p>Just some text inside of the block.</p>
</div>
</div>
You need to have valid html element nesting, and you should probably accomodate for more than one of these sections. Here is an example.
function getID(el) {
var x = el.getElementsByClassName("blueblock")[0].id;
document.getElementById(el.id).innerHTML = x;
}
.blueblock {
width:30%;
height:50vh;
float:left;
background-color:lightblue;
text-align:justify;
overflow:auto;
}
<div id="xx" ondblclick="getID(this)">
<div class="blueblock" id="bluebl">
<p>Just some text inside of the block.</p>
</div>
</div>
<div id="xx2" ondblclick="getID(this)">
<div class="blueblock" id="bluebl2">
<p>Just some more text inside of the block.</p>
</div>
</div>
The first p element is basically terminated by the next div element because a p (paragraph equivalent) cannot contain divs. Hence the double click code is not seen because effectively the first p element has no content.
Replacing that p element by a div, and terminating correctly, means that anything within the div will lead to the double click being seen.
However, note that ondblclick is not supported by all browsers (see https://caniuse.com/?search=ondblclick) so we replace that by adding an event listener to the element using Javascript.
Here is the complete snippet. Note that when you have double clicked the innerHTML gets replaced and therefore if you doubleclick again you will see an error in your browser's console as the element cannot be found - it is no longer there.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script>
function getID() {
var x = document.getElementsByClassName("blueblock")[0].id;
document.getElementById("xx").innerHTML = x;
}
</script>
<style>
.blueblock {
width: 30%;
height: 50vh;
float: left;
background-color: lightblue;
text-align: justify;
overflow: auto;
}
</style>
</head>
<body>
<div id="xx">
<div class="blueblock" id="bluebl">
<p>Just some text inside of the block.</p>
</div>
</div>
<script>
document.getElementById('xx').addEventListener('dblclick',getID);
</script>
</body>
</html>
I have several HTML elements that I need to display a tooltip on hover. These are not conventional HTML elements and come from a generated script on the backend, which I do not have permissions to alter. What I want to know, from a front end perspective, is how I can display a tooltip without declaring this in the HTML.
I tried using Bootstrap tooltips, but you need to declare this in the HTML tag as a title, so it's not useful. So, as the example shows below, I need some text saying 'Action' to appear in a tooltip when you hover over the 'Action' element that contains 'should'. Same will be applied when you hover over the text 'approximate number of' contained in the 'Quantifier' element - the word 'Quantifier' should be displayed. Hope this makes sense.
<body>
One string that <Action>should</Action> work is
<Quantifier>approximate number of</Quantifier> other things.
<script>
$(document).ready(function(){
$("Action").hover(function(){
});
$("Quantifier").hover(function(){
});
});
</script>
<body>
So far non-conclusive, as I can only change CSS values and not tooltip text.
You can try updating the title property on those elements. One thing to note is that HTML tags will appear in lowercase when compiled.
$(document).ready(function() {
var style = document.createElement('style');
style.type = 'text/css';
$('head')[0].appendChild(style);
style.innerHTML =
`action, quantifier {
position: relative;
display: inline-block;
margin-top: 20px;
}
action[title]:hover:after, quantifier[title]:hover:after {
content: attr(title);
position: absolute;
top: -100%;
left: 0;
}
action[title]:hover:after {
color: red;
border: solid 1px black;
}
quantifier[title]:hover:after {
color: blue;
border: solid 1px black;
}`;
$('action')[0].title = 'Action';
$('quantifier')[0].title = 'Quantifier';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
One string that <Action>should</Action> work is
<Quantifier>approximate number of</Quantifier> other things.
</body>
add a tooltip for an tag with JS/jQuery without change the html structure. You can modify the css based on requirement.
jQuery(function($){
//If you are able to add class then use $('.add_tooltip').hover
// use $('Quantifier, Action').hover
$('Quantifier, Action').hover(
function () {
//let text = $(this).html(); //this is for html content of hover element
let text = $(this).prop("tagName");
//Add the tag name of hover element to tooltip div
$(this).append('<div class = "tooltip">'+text+'</div>');
//display the tooltip with animation.
$(this).find('.tooltip').hide().fadeIn('slow');
},
//On hover out remove the tooltip.
function () {
$(this).find('.tooltip').remove();
}
);
});
Quantifier, Action{
cursor: pointer;
position:relative;
}
.tooltip{
display: inherit;
background: black;
margin: auto;
padding: 10px;
position: absolute;
z-index: 1000;
width: 200px;
height: 40px;
color: #fff;
top: 18px;
left:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
One string that <Action>should</Action> work is
<Quantifier>approximate number of</Quantifier> other things.
I've been sitting with this problem for like 2 hours. What I'm trying to make is a website where you push a button and it changes color. I know this can be done with CSS, but I'm not interested in that.
The main problem is that when I push the button, nothing happens.. However, if I remove the ' #sug from the css' everything works perfectly... So what I want to do, is to make the layout very basic at the beginning, so there's nothing to it, except like the black background, and when I push the buttons it should switch..
Also, I know you can implement onclick in the button tag, but that's not what I'm going for either. I want to know WHY this happens and how I can resolve this problem.
Here's my javascript, CSS and HTML code:
window.onload = setUp;
function setUp() {
document.getElementById("normal").onclick = setNormalStyle;
document.getElementById("crazy").onclick = setCoolStyle;
document.getElementById("insane").onclick = setInsaneStyle;
}
function setNormalStyle() {
var messageBox = document.getElementById("sug");
messageBox.className = "normal";
}
function setCoolStyle() {
var savingTheSecondVar = document.getElementById("sug");
savingTheSecondVar.className = "cool";
}
function setInsaneStyle() {
var savingTheThirdVar = document.getElementById("sug");
savingTheThirdVar.className = "insane";
}
#sug {
background-color: black;
}
.normal {
height: 500px;
background-color: blue;
color: white;
padding: 30px;
margin: auto;
width: 500px;
}
.insane {
height: 500px;
background-color: green;
padding: 30px;
margin: auto;
width: 500px;
color: white;
}
.cool {
height: 500px;
background-color: red;
padding: 30px;
margin: auto;
width: 500px;
color: white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="Struktur.css" />
<script type="text/javascript" src="struktur.js"></script>
<title>My first Javascript project</title>
</head>
<body>
<div id="sug" class="cool insane normal">
<header>
<h1> Welcome to this Javascript site! </h1>
</header>
<section>
<p>
text
</p>
</section>
<button type="button" id="normal">First style</button>
<button type="button" id="crazy">Second style</button>
<button type="button" id="insane">Third style</button>
</div>
</body>
</html>
The problem is your CSS.
#sug{
background-color: black;
}
Overrides the background-color of your classes because it is a more specific selector (i.e. an id selector).
change the rest of your classes in the css to include the id like
#sug.normal, #sug.insane, #sug.cool etc.
Here is a nice article on CSS specificity to help you understand more: https://css-tricks.com/specifics-on-css-specificity/
That's because an id has preference over a class. You will need to specify it like this:
#sug.cool { background: red; }
etc.
You are not removing the background-color provided by the #sug id in CSS onClick() events of the buttons.
Id has more preference over classes
It is a good habit to use below code as classes has spaces between them and it can be used if you want to add more than one class.
messageBox.className += " " + "normal";
I've this code :
jQuery(document).ready(function($) {
document.getElementById('HAVEATESTHERE').className = "newClass";
}
I want to add a class to #HAVEATESTHERE in javascript, it does not work
Am I missing something ?
You can use classList.add method:
document.getElementById('HAVEATESTHERE').classList.add('first','second', ... );
Also, please make sure you add your class after DOM is rendered.
Take into account, that element.className = 'someClass' will override existing classes with someClass.
elementid is your element`s id and yourclass is that what class do you want add this element.
jQuery(document).ready(function($) {
$('#elementid').addclass('yourClass');
}
Code is fine, see this demo
Ensure that it is either
Added in the window.onload section
window.onload = function(){
document.getElementById('HAVEATESTHERE').className = "class1";
};
if there are already some classes for this element (as suggested by your updated OP), then use classlist to add a new class to that list
document.getElementById('HAVEATESTHERE').classList.add("class1");
- Or the script section is added at the end of body after all the markup is already loaded.
make sure you don't have duplicate IDs for divs. Check this:
function myFunction() {
document.getElementById("myDIV").className = "myclass";
}
.myclass {
width: 200px;
height: 100px;
background-color: blue;
text-align: center;
color: white;
margin-bottom: 10px;
}
<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 300px;
height: 100px;
background-color: coral;
text-align: center;
font-size: 25px;
color: white;
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>Click the button to add a class for div.</p>
<div id="myDIV">
Sample div
</div>
<button onclick="myFunction()">Add Class</button>
</body>
</html>
Basically you are trying to mix JavaScript inside jQuery function. Please take care of that. And if you are only using jquery then please use your code
As in this formate
$(document).ready(function(){
$('#HAVEATESTHERE').addclass('newClass');
}
use addclass() function to add class to your div.
with simple js please try to use anonymous function like this
(function(){
var d = document.getElementById("HAVEATESTHERE");
d.className = " newClass";
})();
I have code like this :
HTML:
<div id="myDiv" class="container">
....
</div>
CSS:
div.container {
width: 300px;
height: 400px;
border: solid 1px black;
overflow: hidden;
background: #efefef;
}
JS:
var myDiv = document.getElementById("myDiv");
var pageWidth = parseInt(myDiv.style.width);
I want to read css property and I can change value using js.
I have tried search with google, and my js code from link of google.
After I check the problem with safari's web inspector, there is problem in that I give sign for js code.
Why is that wrong?
var width = parseInt($('#myDiv').width(), 10);
You probably want to use css:
$("#myDiv").css("width","yourWidthhere");
To get the width of an element, just use:
$("#yourElementId").width();
try this
alert($('yourdiv').width());
live demo here
You may try this :
$("#myDiv").css("width","100%");
You can't get the class property using this code.
var myDiv = document.getElementById("myDiv"); var pageWidth =
parseInt(myDiv.style.width);
I am going with a jquery way, here is the sample code:
<html>
<head>
<style>
div.container { width: 300px; height: 400px; border: solid 1px black; overflow: hidden; background: #efefef;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
</head>
<body><div id="myDiv" class="container"> hi...</div></body>
</html>
Then you should able to get and set the width using the jquery methods:
$("#myDiv").width(); //Get
$("#myDiv").width(500); //Set