I just want to make a URL with a button when It clicks it must show a dialog with my message. Is there any way to achieve in HTML?. Already searched google, as a beginner I don't understand much. So a simple tutorial might help me.
the link should be like www.google.com/webpage/#popup
dialog must be shown in the center of the screen.
onClick with a function:
<script type="text/javascript">
function AlertIt() {
alert("ATTENTION! THIS IS AN ALERT");
}
</script>
click me
Complex single one-liner:
<a href="http://example.com/"
onclick="return alert('Please click on OK to continue.');">click me</a>
You can make use of a hashchange-event!
Make a check-hash function and call it initially, so that loading the URL with the hash has the same behavior as changing the hash when already on-page.
You could create an array holding the IDs of the elements that should "listen" for such a hashchange, and give them a specific class (e.g. .hash-selected) when their ID equals the hash.
const hashes = ["#popup"]; // List of IDs that are "listening"
let lastHash = "";
function checkHash() {
if (hashes.includes(lastHash)) // Remove class from last selected element
document.querySelector(lastHash).classList.remove("hash-selected");
if (hashes.includes(location.hash)) // Add class to current selected element
document.querySelector(location.hash).classList.add("hash-selected");
// Save current hash as 'lastHash' for first if-statement when calling 'checkHash()' again
lastHash = location.hash;
}
checkHash(); // Initial function-call for same behavior on "page-open"
window.addEventListener("hashchange", () => checkHash());
body {margin: 0}
#popup {
position: absolute;
border-bottom: 1px solid black;
width: 100%;
transform: translateY(-100%);
background: lightgreen;
}
#popup.hash-selected {transform: translateY(0)}
<div id="popup">
<p>Some sample text</p>
Close
</div>
Open popup
We could even easily fill the hashes-array with IDs of elements that have a specific class, like .hash-listen:
const hashes = [];
for (let el of document.querySelectorAll(".hash-listen"))
hashes.push("#" + el.id);
// ...
Sidenote
To remove hashchanges from the browser-history, you should take a look at this answer that demonstrates the history.replaceState()-function.
Click Here
<script>
function myAlert() {
alert('hello there!');
}
</script>
Related
I have a site with a lot of different div. The thing they have in common is all share (besides their unique classes) a shared class. Lets just call it .changeClass.
What I am looking for is code with a button (or radio buttons) and by clicking the button, the background instance of all these divs will get the same one (which the .changeClass has). So the .changeClass will just be active when the button is toggled/clicked.
I am looking for a way to do this with pure javascript and no Jquery.
Sorry for being a noob :-)
In the solution below, clicking the <button> element will add/remove the class style .changeClass to all elements that have the class style .apply applied.
let button = document.getElementById('change');
let containers = document.getElementsByClassName('apply');
function changeButtonText() {
if(button.innerHTML === "Add")
button.innerHTML = "Remove";
else
button.innerHTML = "Add";
}
button.addEventListener('click', function() {
for(let index = 0 ; index < containers.length ; ++index)
containers[index].classList.toggle('changeClass');
changeButtonText();
});
div {
margin-top: 25px;
}
.apply {
border: 3px solid black;
}
.changeClass {
background-color: black;
color: white;
border: 3px solid red;
margin-top: 25px;
}
<button id="change">Add</button>
<div class="apply">1</div>
<div class="apply">2</div>
<div class="apply">3</div>
<div class="apply">4</div>
<div class="apply">5</div>
First lets get all divs that are on the DOM
const divs = document.getElementsByTagName("div");
You will have array of all the divs that are on the DOM. Then add your class to all of it. In order to do that, lets loop it.
divs.forEach(div => div.className += div.className + " changeClass");
Could this be what you are looking for?
In html:
<button onclick="changeColor('blue');">blue</button>
In JS
function changeColor(newColor) {
var elem = document.getElementsByClassName("changeClass");
elem.style.color = newColor;
}
The HTML color can be any color you would like it to be, just change they name from blue to any color or input a hex code.
We have multiple divs with the same class value
We have given a function to the button that we want the event to happen when it is clicked, using the onclick method. Now when we click the button, the function called myFunction will run.
HTML:
<div class="changeClass">Im Example Div</div>
<div class="changeClass">Me Too</div>
<button type="submit" onclick="myFunction()">Click To Change Div BgColors !
</button>
We must define myFunction as Javascript and change the background color.
We have defined a function called myFunction.
With the getElementsByClassName selector in our function, we got all the data with the class value changeClass in object format.
To add a background (or any css property) to all of these objects; We put the object in a for loop and now we split our elements.
We can now define a background color for our elements with the style.backgroundColor parameter.
JavaScript:
function myFunction(){
var divs = document.getElementsByClassName('changeClass');
for(var i=0; i< divs.length; i++){
divs[i].style.backgroundColor = 'red';
}
}
For more detailed information, you can refer to the resources: https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
Don't be sorry for being new at something and wanting to learn more!
So what you are saying is that the divs you want to change all have a common class of "changeClass". If this is the case then you want a function is passed an argument value of the color you want to be changed. Since all of your divs are static and you probably don't plan on changing, declare a variable outside of this function that has the following code
const divs = document.getElementsByClassName("changeClass")
Then, inside of the function, loop through all of the divs collected inside the variable "divs", or whatever you want to call it. Since "getElementsByClassName" returns a collection, it does not have the built in "foreach" and "map" methods. So you have to use a for loop preferably the following.
const divs = document.getElementsByClassName("changeClass");
function changeColor(color) {
for (let element of divs) {
element.style.backgroundColor = color;
}
}
I may have interpreted this wrong but I hope it helps
You may find using a CSS variable helpful.
For example:
function bg(color) {
document.body.style.setProperty('--bg', color);
}
body {
--bg: cyan;
}
.container {
display: flex;
gap: 1vw;
}
.container div {
width: 100px;
height: 100px;
background-color: black;
}
.container div.changeClass {
background-color: var(--bg);
}
<body>
<button onclick="bg( 'red');">Red</button>
<button onclick="bg( 'green');">Green</button>
<button onclick="bg( 'blue');">Blue</button>
<button onclick="bg( 'black');">Black</button>
<div class="container">
<div class="changeClass"></div>
<div class="changeClass"></div>
<div class="changeClass"></div>
<div></div>
<div class="changeClass"></div>
</div>
</body>
Then when one of the radio buttons is clicked it sets the variable --bg.
Here's a simple snippet:
First of all - thank you for all your replies. And yes I should have included code. I tried so many things that i just gave up at som point - got confused what was right code and what was just rubbish. So I appreciate so much that you all took time to answer me. This was my first post so now I know for the future. The answers I got all was possible ways to solve my problem - so thank you all. I will do better next time. You are awesome...
BTW - All solutions seems to work - but can only checkmark one of them as you know.
You can add or remove a class to change the colours of different div:
document.queryselector('.className').classList.add('classNamethatyouwanttoadd');
document.queryselector('.className').classList.remove('classNamethatyouwanttoadd');
So I am dynamically generating HTML code with JavaScript that loads in all my images from my Firebase Realtime Database. I'm currently working on implementing a button attached to each image that will delete this image when clicked. However, after multiple attempts to grab this div's ID attribute using both standard JavaScript and Jquery, the id in the alert box is always 'undefined'. Inspecting the webpage allows me to see that the image's id is always loaded in just fine, so I know it is there.
This is the HTML Generated that I'm trying to interact with.
JavaScript function to respond to my html 'onclick event'
function deleteFile(){
var postId = $(this).closest('div').attr('id');
alert("You have selected id: " + postId);
var sure = confirm("Are you sure you want to delete this post?");
if(sure){
firebase.database().ref().child('Posts/' + postId).remove().then(function(){
alert("Post deleted sucessfully");
});
}
};
Attached image is what html is generated on the actual chrome inspector. The ID's of course will all be unique.
add this parameter on your html onclick attribute so it become deleteFile(this)
then on your js
function deleteFile(element){
var postId = $(element).closest('div').attr('id');
alert("You have selected id: " + postId);
var sure = confirm("Are you sure you want to delete this post?");
if(sure){
firebase.database().ref().child('Posts/' + postId).remove().then(function(){
alert("Post deleted sucessfully");
});
}
};
Pairing onclick with $(this) won't work as you expect because $(this) has a different context, you could view its value using console.log($(this));
What should be done is add a class to that button and bind an onclick event via jquery. Run snippet below.
Red div contains onclick event attached via jquery.
Yellow div contains onclick event attached to the button attribute onclick.
$(document).ready(function(){
$(".getIdButton").click(function() {
alert($(this).closest("div").attr("id"));
});
});
function getId() {
alert($(this).closest("div").attr("id"));
console.log($(this));
}
div {
width: 100px;
height: 100px;
padding: 20px;
display: inline-block;
}
#red {
background-color: red;
}
#yellow {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="red">
Just a link
<button class="getIdButton">Click Me</button>
</div>
<div id="yellow">
Just a link
<button onclick="getId()">Click Me</button>
</div>
I was interested in creating a temporary screen before a page where someone could choose an option that would determine what they're shown.
Example: Contact page where the screen asks "Are you interested in contacting us regarding a purchase or to talk to our customer team". Once they click an option it would display the corresponding contact form (one emails customer team, the other emails the purchase team).
I'm not sure how to code this as I'm new to HTML/CSS/JavaScript but based on what I've learned so far I'm assuming this is more advanced JavaScript.
I can provide a simple example to give you some sense about it, but I would suggest you to get more basic front end training first.
if (window.confirm('Do you want load form a?')) {
document.getElementById('a').style.display = 'block';
} else {
document.getElementById('b').style.display = 'block';
}
https://jsfiddle.net/8LmL4vdr/1/
I'm not entirely sure what you asking, but it sounds like if you changed the elements' z-index values on the click of the buttons, it would work.
You can read more about z-index here.
Or, you can use display.
Here is an example:
function layerPages(page) {
if (page == "one") {
document.getElementById("pageOne").style.display = "block"; // shows first page if that is what is called
} else if (page == "two") {
document.getElementById("pageTwo").style.display = "block"; // shows second page if that is what is called
} else {
window.alert("error, wrong useage");
}
document.getElementById("originalPage").style.display = "none"; // hides main page
}
document.getElementById("buttonOne").addEventListener("click", function
myfunction() {layerPages("one");}); // adds event listener that states that when the first button is clicked, the first page is shown and the original is hidden using the function "layerPages" (declared above)
document.getElementById("buttonTwo").addEventListener("click", function
myfunction() {layerPages("two");}); // adds event listener that states that when the second button is clicked, the second page is shown and the original is hidden using the function "layerPages" (declared above)
#originalPage {
background-color: black;
width: 100px;
height: 100px;
}
#pageOne, #pageTwo {
display: none; /*You need to make sure that both #pageOne and #pageTwo start out as display: none;*/
background-color: yellow;
width: 100px;
height: 100px;
}
#pageTwo {
background-color: orange;
}
<div id="originalPage">
<button id="buttonOne">Page One</button>
<button id="buttonTwo">Page Two</button>
</div>
<div id="pageOne"></div>
<div id="pageTwo"></div>
<!--The content goes into each div, I'm sure that you can figure that out-->
I am working on a class project and need to be able to toggle the background color of a transparent png on click. I have been working through a number of examples from the site, but I can't get it working. I am a total novice at Javascript and haven't had luck trying to plug in jQuery code either.
Here is the targeted section:
<div class="expenseIcon"><a href="#">
<img src="images/mortgage.png"></a><br/>
<p>Rent or Mortgage</p>
</div>
On clicking the linked image, the goal is for the background on the image to change to green. Clicking it again would change it back to the default, white. Here's the CSS I'd like to toggle on/off with click.
.colorToggle {
background: #A6D785;
}
I had tried adding class="iconLink" to the href and class="iconBox" to the image with the following Javascript adapted from another post, but it didn't work.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
//alert(obj.var1);
//return false;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
Any advice would be greatly appreciated!
Let's break down what is happening with your current code when you click the link.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
JQuery finds all elements with the classname "iconBox". In your case, this is the img element. The reference to that element is then saved in "obj.var1". You do not end up doing anything with this reference, so these two lines can be removed.
All elements with the class "iconBox" have the class "colorToggle" removed. Your img element didn't have this class on it, so nothing happens.
The class "colorToggle" is added to the anchor element. Yes! Now the element wrapping the img has a background color.
Unfortunately, clicking the anchor tag again won't do anything, since the anchor tag will already have the "colorToggle" class and all we would be doing would be trying to add it again. Hmm. Let's try changing addClass to toggleClass. Here's our new code:
$(document).ready(function () {
$(".iconLink").click(function () {
$(this).toggleClass('colorToggle');
}
});
Also, note that because we're working with the anchor element, the p element won't be affected by this change. If you want the entire div to change background colors, use this line instead:
$(".expenseIcon").toggleClass('colorToggle');
Using the given markup:
<!-- to toggle the bg-color onClick of anchor tag -->
<div class="expenseIcon">
<a href="#">
<img src="images/mortgage.png">
</a>
<br/>
<p>Rent or Mortgage</p>
</div>
since the question asks for javascript, heres an option for updating the background-color of an element using the built-in js.style method
//get a handle on the link
//only one element w/ className 'expenseIcon'
//first child of 'expenseIcon' is the anchor tag
var link = document.getElementsByClassName('expenseIcon')[0].children[0];
//get a handle on the image
var image = link.children[0];
//listen for click on link & call bgUpdate()
link.addEventListener('click', bgUpdate, false);
function bgUpdate() {
if(image.style.backgroundColor === 'lightgoldenrodyellow'){
image.style.backgroundColor = 'aliceblue';
} else if (image.style.backgroundColor === 'aliceblue') {
image.style.backgroundColor = 'lightgoldenrodyellow';
}
else console.log('image bgColor: ' + image.style.backgroundColor);
}
a similar example
css
.expenseIcon{
background: red;
}
.colorToggle {
background: blue;
}
jquery
$(".expenseIcon").click(function () {
$('.expenseIcon').toggleClass('colorToggle');
});
By default, the div will have expenseIcon background. ToggleClass will toggle the div class with colorToggle so will override the previous color.
You don't need an hyperlink tag A to manage clicks, just put it on the DIV.
I am implementing an User Interface for a project I'm working on and can be found here : Toobrok
Each time the mouse of the user enters a div, a class is added to this div to highlight it, I use the stopPropagation() method to restrict the highlighting to the div whose z-index is higher (the top div in the z axis).
However, sometimes, my user needs to select an element hidden by another one, when the dimensions of the 2 elements are different, and if the bottom div is larger, he can find some points of the bottom div not hidden by the top one, but when the dimensions are the same, I would like the user to be able to press a key to change the depth (on the z-axis) of his selection.
The relevant code is given below (in CoffeeScript), but a javascript solution would also help me:
Ui.bind = (elements, index) ->
ids = Ui.getIdSelector(elements)
$(ids).attr("centroid", index)
$(ids).mouseover (event) ->
event.stopPropagation()
Ui.highlight $(ids)
$(ids).mouseout (event) ->
event.stopPropagation()
Ui.resetHighlight $(ids)
I hope the question is clear and looking forward to your answer.
This is an example of HTML to consider :
<!DOCTYPE html>
<html>
<head>
<title> Sample page </title>
</head>
<body>
<div id="container">
<div id="child1">Some text...</div>
</div>
</body
</html>
And the related css :
#container {
height: 200px;
width: 500px;
}
#child1 {
height: 90%;
width: 90%;
}
When the mouse enters the child1 element, this element is highlighted, I want the container element to highlight when the user press a specific key.
I could use the JQuery parent() function to select that element on this example, but I am not sure it is a good solution, sometimes, the parent can have a size of 0px and and then a mouseover on this element would not be consistent. I want to select the element normally selected by Javascript if I do not use the stopPropagation() event.
I actually just found something that might help :
How to undo event.stopPropagation in jQuery?
But I cannot use that in my case... Because my condition is another user action, and I cannot synchronously wait for an user to do something.
I started writing code but then decided to leave implementation to you. Here is the text explanation:
At some point of time (probably when user press button to cycle through all hovered elements) you have to find all candidates for highlighting. There is no other way to do it rather than manually loop through all your elements and check if mouse position is inside their bound rect. You can get mouse coordinates from argument in mouseover callback. Save all these hovered elements in some array.
Next, you have to manually choose which element to highlight. Just highlight the first element in saved array and move the element to the end of array. You also may want to increase this element z-index and add callback for mouseout to this element.
Hope it helps, feel free to ask if you need more details.
You could use the CSS property pointer-events to make the child insensitive. Then events will be targeted to the element displayed below. For simple highlighting you should use pure CSS, however, jQuery can be helpful not to highlight the parent element as well while child is hovered without Ctrl.
Some example (also uploaded to JSFiddle, click into the output pane to make it responsive for keyboard events):
<div id="container1" class="container">
<div id="child1" class="child">Some text...</div>
</div>
div { border:1px dashed red; } /* for demo */
.container
{ height: 200px;
width: 500px;
}
.child
{ height: 90%;
width: 90%;
}
.insensitive
{ pointer-events:none;
}
.container:hover:not(.no-hilight),
.child:hover
{ background-color:yellow;
}
/* other color for demo */
.child:hover{ background-color:green; }
// make events passthrough child when <Ctrl> is held down
$(document).on('keydown keyup', function(ev) {
if (ev.key === 'Control') // for performance
$('.child')[ev.ctrlKey?'addClass':'removeClass']('insensitive');
});
// don't hilight container when child is hovered
$('.child').on('mouseover', function(ev)
{
$('.container').addClass('no-hilight');
});
// never suppress hilight when container is hovered directly
$('.container').on('mouseover', function(ev)
{ if(ev.target === ev.currentTarget)
$('.container').removeClass('no-hilight');
});
// just test which element a click is targeted to
$(document).on('click', function(ev)
{ console.log('click:', ev.target);
});
var preId = 0;
function makeBlack(id)
{
if(id)
{
$('#'+id).css('border-color','black');
}
}
function makered(id)
{
$('#'+id).css('border-color','red');
}
$(document).ready(function(){
$('div').mouseout(function() {
var currentid = this.id;
makeBlack(currentid);
preId = currentid;
});
$('div').mouseleave(function() {
var currentid = this.id;
makeBlack(currentid);
preId = currentid;
});
$('div').mouseover(function() {
var currentid = this.id;
makeBlack(currentid);
makered(preId);
preId = currentid;
});
$('div').mouseenter(function() {
var currentid = this.id;
makered(currentid);
preId = currentid;
});
});
Have you tried something like this for the CSS?
#container.hover{
height: 200px;
width: 500px;
//add a background-color to that element since its a div element
//background-color: (colour)
}
i should hope that the div element would automatically highlight the container div with whichever color you have selected