I was wondering if there is a way to add new data-category to existing one once click event would happen?
I want to add it since I am using it as a filtering element.
An example below: Click the button and add the category: Delta
<div class="item" data-category="Alfa , Beta , Gamma ">
<p> Object 1<p>
<div>
<button class="my-fav">
You can get attributes of the element and change it then set it again, here is an example:
<div id="data" class="item" data-category="Alfa , Beta , Gamma ">
<p> Object 1<p>
</div>
<button id="myButton" class="my-fav">
<script>
const data = document.getElementById("data");
const button = document.getElementById("myButton");
let data_attribute = data.getAttribute("data-category");
myButton.addEventListener("click", function() {
data_attribute += ", Delta";
data.setAttribute("data-category", data_attribute);
});
</script>
Related
My problem is that I have a website, using javascript I have made it when I click on the About Me it opens, but when I click on Education and Achievements the About me button's content remains open and the Education stuff overlaps it. I want to make it so that when I click on another button the first one closes (its content. The website name is dirieahmed.ml
My code HTML and JS will be linked below ill add CSS later if need be.
<div class="container">
<button id="one" class="click one">About Me</button>
<div class="list-1 sec">
<h1 class="content-header-one content">Dummy text header</h1>
<p class="content-paragraph-one">Dummy text</p>
</div>
<button class="click two">Education and Achivements</button>
<div class="list-2 sec">
<p class="content-paragraph2 content">Dummy text</p>
<ul class="content-list content">
<li>- Achivement #1</li>
<li>- Achivement #2</li>
<li>- Achivement #3</li>
</ul>
</div>
<button class="click three" >Other</button>
<div class="list-3 sec">
<h1 class="content-header-two content">Dummy text header</h1>
<p class="content-paragraph3 content">Dummy text</p>
</div>
<script async>
let one = document.querySelector('.one');
let two = document.querySelector('.two');
let three = document.querySelector('.three');
let list1 = document.querySelector('.list-1');
let list2 = document.querySelector('.list-2');
let list3 = document.querySelector('.list-3');
one.addEventListener("click", ()=>{
list1.classList.toggle('newlist');
});
two.addEventListener("click", ()=>{
list2.classList.toggle('newlist');
lis
})
three.addEventListener("click", ()=>{
list3.classList.toggle('newlist')
});
// please change above
</script>
</div>
To summarize you will need to hide all other ones when there is a click anywhere and then only show the ones based on the link that you clicked
Check the code below
https://codesandbox.io/s/keen-driscoll-igzlwb?file=/index.html:2333-3356
<script async>
// Instanciate List div's
let list1 = document.querySelector(".list-1");
let list2 = document.querySelector(".list-2");
let list3 = document.querySelector(".list-3");
// Reset's all views to the default without .newlist
const resetAllViews = () => {
list1.classList.remove("newlist");
list2.classList.remove("newlist");
list3.classList.remove("newlist");
};
// Checks to see what button is clicked and shows correct list based on input
document.addEventListener(
"click",
function (e) {
e = e || window.event;
var target = e.target;
if (target.classList.contains("one")) {
resetAllViews();
list1.classList.add("newlist");
}
if (target.classList.contains("two")) {
resetAllViews();
list2.classList.add("newlist");
}
if (target.classList.contains("three")) {
resetAllViews();
list3.classList.add("newlist");
}
}, false);
</script>
The document object should be given a click event listener.
Use the contains() function to determine with each click if the clicked element is outside the targeted element.
Hide the original element if the clicked element is outside.
I'm writing the code to edit a database table.
I have the following HTML:
<div id="1">
<div contenteditable>aaa</div>
<div contenteditable>bbb</div>
<div contenteditable>ccc</div>
<button onClick="a('save')">SAVE</button>
<button onClick="a('delete')">DELETE</button>
</div>
<div id="2">
<div contenteditable>ddd</div>
<div contenteditable>eee</div>
<div contenteditable>fff</div>
<button onClick="a('save')">SAVE</button>
<button onClick="a('delete')">DELETE</button>
</div>
<div id="3">
<div contenteditable>ggg</div>
<div contenteditable>hhh</div>
<div contenteditable>iii</div>
<button onClick="a('save')">SAVE</button>
<button onClick="a('delete')">DELETE</button>
</div>
And so on.
Using the following function, I can get the clicked button:
function a(value) {
console.log(value);
}
When a button (SAVE or DELETE) is clicked, I need to retrieve:
the id of the "parent" div;
the content of each of the three contenteditable divs inside the same "parent" div.
Is it possible using pure Javascript?
Any suggestion will be very appreciated.
Thanks in advance.
What I would do is implement click listeners in JS, that way I can query elements easily.
Here is the example:
// Query all div.div-editable elements
document.querySelectorAll('div.div-editable')
.forEach((div) => {
// The id of the parent
const divId = div.id;
// Each of content editable divs inside the parent div
const editables = div.querySelectorAll('div[contenteditable]');
// The buttons Save and Delete
const saveBtn = div.querySelector('button.button-save');
const deleteBtn = div.querySelector('button.button-delete');
// Add click listeners to buttons
saveBtn.addEventListener('click', function() {
console.log('Saved: ' + divId);
const contentOfEditableDivs = Array.from(editables).map((div) => div.innerText);
console.log('Values of divs:', contentOfEditableDivs);
});
deleteBtn.addEventListener('click', function() {
console.log('Deleted: ' + divId);
const contentOfEditableDivs = Array.from(editables).map((div) => div.innerText);
console.log('Values of divs:', contentOfEditableDivs);
});
});
<div id="1" class="div-editable">
<div contenteditable>aaa</div>
<div contenteditable>bbb</div>
<div contenteditable>ccc</div>
<button class="button-save">SAVE</button>
<button class="button-delete">DELETE</button>
</div>
<div id="2" class="div-editable">
<div contenteditable>ddd</div>
<div contenteditable>eee</div>
<div contenteditable>fff</div>
<button class="button-save">SAVE</button>
<button class="button-delete">DELETE</button>
</div>
<div id="3" class="div-editable">
<div contenteditable>ggg</div>
<div contenteditable>hhh</div>
<div contenteditable>iii</div>
<button class="button-save">SAVE</button>
<button class="button-delete">DELETE</button>
</div>
EDIT 1: Added code snippet
EDIT 2: Simplified explanation
You can send this keyword in the argument of click's event handler and then access the parent div's id.
So your HTML would look something like:
// rest of the code here
<button onClick="a(this, 'save')">SAVE</button>
<button onClick="a(this, 'delete')">DELETE</button>
// rest of the code here
And your JS code would change to:
function a(elem, value) {
console.log(elem.parentNode.id);
}
More details on the following link:
how i get parent id by onclick Child in js
I want to be able to modify/output to the content of particular header tag with the id attribute value of whichever anchor/link is clicked.
Currently, i am able to only change the text "City" with the value of the first id ("New York", in the below example) - because the text is outside of the nested div tags, but still within the anchor tags. so the first link works, but the 2nd and 3rd links pass empty strings/give no output. i want to the text/content to remain within the div tags as in the 2nd and 3rd links.
<base target=splash>
<H3 id=myTitle onclick="myFunction()">City</H3>
<a class="clickable" href="myPage.htm?id=108" id="New+York">New York
<div class=cityWrap>
<DIV class=cityNo>108</DIV>
<DIV class=cityName>New York</DIV>
<DIV class=country>USA</DIV>
</div>
</a>
<a class="clickable" href="myPage.htm?id=110" id="Shanghai">
<div class=cityWrap>
<DIV class=cityNo>110</DIV>
<DIV class=cityName>Shanghai</DIV>
<DIV class=country>China</DIV>
</div>
</a>
<a class="clickable" href="myPage.htm?id=112" id="Damascus">
<div class=cityWrap>
<DIV class=cityNo>112</DIV>
<DIV class=cityName>Damascus</DIV>
<DIV class=country>Syria</DIV>
</div>
</a>
<IFRAME src="myPage.htm" name=splash></IFRAME>
<script>
window.addEventListener('load', () => {
let myFunction = event => {
let clickedElem = event.target;
document.getElementById('myTitle').innerHTML = clickedElem.id;
};
for (let elem of document.getElementsByClassName('clickable')) elem.addEventListener('click', myFunction);
});
</script>
Step 1: Add listeners to all required elements
You have a couple of options.
You could exhaustively list all clickable ids in your javascript:
let ids = [ 'New York', 'Shanghai', 'Damascus' /* ... */ ];
for (let id of ids) document.getElementById(id).addEventListener('click', myFunction);
You could target the clickable elements by the fact that they are all a elements:
for (let elem of document.getElementsByTagName('a')) elem.addEventListener('click', myFunction);
You could attach a common class for all desired a elements, and use document.getElementsByClassName:
html:
<a class="clickable" href="myPage.htm?id=New York" id="New York">New York</A>
<a class="clickable" href="myPage.htm?id=Shanghai" id="Shanghai">Shanghai</A>
<a class="clickable" href="myPage.htm?id=Damascus" id="Damascus">Damascus</A>
js:
for (let elem of document.getElementsByClassName('clickable')) elem.addEventListener('click', myFunction);
Step 2: Determine which element was clicked inside of myFunction:
Now the same function, myFunction, gets called no matter which element is clicked. We have to figure out which specific element was clicked, to determine which id to display.
Fortunately Event.target does this for us. We can rewrite myFunction to look like this:
let myFunction = event => {
// Get the <a> element that was clicked
let clickedElem = event.target;
// Apply that element's id as the innerHTML of the #myTitle element
document.getElementById('myTitle').innerHTML = clickedElem.id;
};
Final code
Could look something like this:
window.addEventListener('load', () => {
let myFunction = event => {
let clickedElem = event.target;
document.getElementById('myTitle').innerHTML = clickedElem.id;
event.preventDefault(); // Important to prevent page navigation
};
for (let elem of document.getElementsByTagName('a')) elem.addEventListener('click', myFunction);
});
[href$="=108"], [href$="=108"] * { background-color: #ffa0a0; }
[href$="=110"], [href$="=110"] * { background-color: #a0ffa0; }
[href$="=112"], [href$="=112"] * { background-color: #a0a0ff; }
a > div { pointer-events: none; }
<h3 id=myTitle>City</H3>
<a href="myPage.htm?id=108" id="New+York">New York
<div class=cityWrap>
<DIV class=cityNo>108</DIV>
<DIV class=cityName>New York</DIV>
<DIV class=country>USA</DIV>
</div>
</a>
<a href="myPage.htm?id=110" id="Shanghai">
<div class=cityWrap>
<DIV class=cityNo>110</DIV>
<DIV class=cityName>Shanghai</DIV>
<DIV class=country>China</DIV>
</div>
</a>
<a href="myPage.htm?id=112" id="Damascus">
<div class=cityWrap>
<DIV class=cityNo>112</DIV>
<DIV class=cityName>Damascus</DIV>
<DIV class=country>Syria</DIV>
</div>
</a>
you can try something like this for each of the links
<a onclick="getElementById('myTitle').innerHTML = your title here">your value here</a>
else try searching for w3schools onclick event
hope this helps :>
apologies if this is a duplicate, but I've searched for this specific question and haven't been able to find it.
Let's say I have 4 paragraphs i want add <h3> element under paragraph that was clicked.
each of paragraphs have same data-name attribute but different value
i tried already $(" <h3 data-price'222'>NEW ITEM</h3>").insertAfter(???);, but i don't know what write in the bracket.
<body>
<div class="container">
<p class="clickable" data-price="5">Apple</p>
<br>
<p class="clickable" data-price="7">Coffee</p>
<br>
<p class="clickable" data-price="9">Water</p>
<br>
<p class="clickable" data-price="10">Pitza</p>
<br>
<h3></h3>
<br>
<button>Reset</button>
</div>
</body>
$(function () {
createCeleb();
})
function createCeleb() {
$('p.clickable').on('click', function () {
var temp = $(this).attr('data-price')
this.temp = temp;
let on1 = $("p").find(`[data-price='${this.temp}']`)
$(" <h3 data-price'222'>NEW ITEM</h3>").insertAfter(on1);
});
}
I expect that after I click on the paragraph
under will be added element
but nothing happen
I want it be dynamic and added only under paragraph that clicked
is it possible?
Your code fails because
let on1 = $("p").find(`[data-price='${this.temp}']`);
does not find and thus return an object at all.
However there is a more elegant way to obtain the object which caused the click event than trying to find it using a data attribute.
If you add the special e parameter to the callback function you can reference the object using e.target.
Here's an example - just click on 'Run code snippet':
$('p.clickable').on('click', function (e) {
var temp = $(this).attr('data-price')
this.temp = temp;
let on1 = e.target;
$(" <h3 data-price'222'>NEW ITEM</h3>").insertAfter(on1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<p class="clickable" data-price="5">Apple</p>
<br>
<p class="clickable" data-price="7">Coffee</p>
<br>
<p class="clickable" data-price="9">Water</p>
<br>
<p class="clickable" data-price="10">Pitza</p>
<br>
<h3></h3>
<br>
<button>Reset</button>
</div>
I think this is what you are looking for. Create a new element from the HTML you had then add after the <p> that was clicked.
$(function () {
createCeleb();
})
function createCeleb() {
$('p.clickable').on('click', function () {
var newele = $.parseHTML("<h3 data-price'222'>NEW iTEM</h3>");
$(this).after(newele)
});
}
Fiddle
I need to recreate and append my template div to the parent div on button click and this can be done multiple times
<div id = "parent">
<div id = "child_1">
<div><input type = "text"></div>
<div><input type = "text"></div>
//several inputs and divs
</div>
</div>
and my script
//on button click event
var template = $("#parent").children().last();
template.attr("id","child_2"); //just a sample of dynamic id
$("#parent").append(template);
But this doesn't work
You need to clone() a copy of the child before you append it, otherwise you just put the current element back in its original position.
var template = $("#parent").children().last().clone();
Working example
Try with this:
var html = $("#parent").html();
var i = 1;
$("button").on("click",function(){
i++;
$("#parent").append(html.replace('id="child_1"','id="child_' + i + '"'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
<div id = "child_1">
<div><input type = "text"></div>
<div><input type = "text"></div>
//several inputs and divs
</div>
</div>
<button>Click</button>