I'm trying to show appropriate content using this method: determine id of the clicked div, than open div content with determined id + '-box'. But it doesn't work.
JQuery that doesn't work:
$(".portfolio-apps section").click(function() {
var currentID = '#' + $(this).attr('id');
console&&console.log(currentID);
var currentIDBox = currentID + "-box";
console&&console.log(currentIDBox);
$(currentID).click(function() {
$('.portfolio-entry-text').hide('fast');
var bcn = $(currentIDBox);
if ($('.box-content').is(':visible')) {
$('.box-content').hide();
bcn.show();
}
else {
$('.box-content').hide();
bcn.slideToggle(200);
}
});
});
Similar JQuery that is working:
$("#gterminal").click(function() {
$('.portfolio-entry-text').hide('fast');
var bcn = $('#gterminal-box');
if ($('.box-content').is(':visible')) {
$('.box-content').hide();
bcn.show();
}
else {
$('.box-content').hide();
bcn.slideToggle(200);
}
});
HTML
<div class="portfolio-apps clearfix">
<section class="button" id="gterminal">
<span>Google in Terminal</span>
</section>
<section class="button" id="MySQLToJSON">
<span>MySQL to JSON</span>
</section>
</div>
<div id="wrapper" >
<div class="box-content" id="gterminal-box">
<p>BOX 1</p>
</div>
<div class="box-content" id="MySQLToJSON-box">
<p>BOX 2</p>
</div>
</div>
You're binding a .click event internally, which means that the -box showing/hiding won't be triggered until a second click. This doesn't make sense to me. If you just remove the internal .click binding, it seems to work quite nicely:
http://jsfiddle.net/Th3wT/
Related
I am trying to hide the div if you click only on the header. But my filter does not seem to work. I get the intended function wherever I click on the div. I want to restrict this to only when you click on the header.
<div class="post" onclick="updatenext()">
<h2>Item3</h2>
</div>
<div class="post" onclick="updatenext()">
<h2>Item4</h2>
</div>
<script>
var index=0;
$(".post").hide();
$(".post").eq(0).show();
// Tried this too: $(".post").filter(":header")....
$(":header.post").on("click",
function () {
index=$(this).index();
//console.log($(this).index());
$(this).hide();
$(".post").eq(index).show();
}
);
</script>
I expect the click to work only when clicking on the header element within each div.
Try using only jQuery for the event listener, like this:
<div class="post">
<h2 onclick="updatenext()">Item3</h2>
</div>
<div class="post">
<h2 onclick="updatenext()">Item4</h2>
</div>
<script>
var index = 0;
$(".post").hide();
$(".post").eq(0).show();
$("h2").on("click", function () {
index = $(this).parent().index();
$(this).parent().hide();
$(".post").eq(index).show();
});
</script>
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 need to display different output according to each different icon clicked without defining separate functions;
HTML:
<p onclick="expand()" id="i1">icon1</p>
<p onclick="expand()" id="i2">icon2</p>
<p onclick="expand()" id="i3">icon3</p>
<div id="blocki1"></div>
<div id="blocki2"></div>
<div id="blocki3"></div>
Can I do something like this with JS?
function expand() {
document.getElementById("block" + this.id).style.display = "block";
}
I've tried the method above which apparently didn't work, I need to a)store icon's id and b) combine the id with string. Don't sure if that's possible.
<p onclick="expand(this.id) id="i1">icon1</p>
<p onclick="expand(this.id) id="i2">icon2</p>
<p onclick="expand(this.id) id="i3">icon3</p>
<div id="blocki1"></div>
<div id="blocki2"></div>
<div id="blocki3"></div>
<script>
function expand(e) {
document.getElementById("block" + e).style.display = "block";
}}
</script>
First.. You have 4 typos. First 3 are that you don't have closing " after onclick="expand()
<p onclick="expand() id="i1">icon1</p>
<!-- There needs to be " after expand() -->
Last typo is you have extra closing } after expand function.
Now, since you're not using addEventListener API, the value of this will not be set on your expand function.
So you need to pass your current element as a parameter to the function.
<p onclick="expand(this)" id="i1">icon1</p>
<p onclick="expand(this)" id="i2">icon2</p>
<p onclick="expand(this)" id="i3">icon3</p>
<div id="blocki1">blocki1</div>
<div id="blocki2">blocki2</div>
<div id="blocki3">blocki3</div>
(Added some place holder text to divs to see if this works)
Lastly, access the current element in your function as a first parameter.
function expand(el) {
document.getElementById("block" + el.id).style.display = "block";
}
Pass parameters to the function
You need to pass some data (e.g. the reference to the object, its name, or whatever else you need) to the function you're calling.
For example, look at the sample code from https://www.w3schools.com/jsref/event_onclick.asp
<p onclick="myFunction(this, 'red')">Click me to change my text color.</p>
<script>
function myFunction(elmnt,clr) {
elmnt.style.color = clr;
}
</script>
I might approach it slightly differently by removing the inline JS, and using classes and data attributes. Here I have classes and data attributes on all the elements. I attach click event listeners to the "buttons" which call the handleClick function. This function checks the data id attribute of the button and grabs the corresponding slide, adding a "show" class to its class list.
const buttons = document.querySelectorAll('.button');
buttons.forEach(button => {
button.addEventListener('click', handleClick, false);
});
function handleClick(e) {
const id = e.target.dataset.id;
const slide = document.querySelector(`.slide[data-id="${id}"]`);
slide.classList.add('show');
}
.slide {
display: none;
}
.show {
display: block;
}
<p class="button" data-id="1">icon1</p>
<p class="button" data-id="2">icon2</p>
<p class="button" data-id="3">icon3</p>
<div class="slide" data-id="1">blocki1</div>
<div class="slide" data-id="2">blocki2</div>
<div class="slide" data-id="3">blocki3</div>
Your code should like this
<p onclick="expand(this) id="i1">icon1</p>
<p onclick="expand(this) id="i2">icon2</p>
<p onclick="expand(this) id="i3">icon3</p>
<div id="blocki1"></div>
<div id="blocki2"></div>
<div id="blocki3"></div>
<script>
function expand(elm) {
document.getElementById("block" + elm.id).style.display = "block";
}
</script>
If you are a beginner, I would suggest you to avoid practice of adding handlers in HTML, before it becomes your coding attitude.
Instead, add eventlisteners for them in js. Separation of concerns is really big theory.
And it's relativelyeasy to deal with this in event handlers
You can read more about it here
var ps = Array.from(document.querySelectorAll("p"));
for(var i=0; i< ps.length; i++){
ps[i].addEventListener(("click"), function(){
document.getElementById("block" + this.id).style.display = "block";
})
}
div{
display: none;
}
<p id="i1">icon1</p>
<p id="i2">icon2</p>
<p id="i3">icon3</p>
<div id="blocki1">This is 1</div>
<div id="blocki2">This is 2</div>
<div id="blocki3">This is 3</div>
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.
<div class="mainContent">
<div class="articleContent">
<h1>header1</h1>
<p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">
</div>
</div>
<div class="mainContent">
<div class="articleContent">
<h1>header2</h1>
<p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore()">
</div>
</div>
And then the JS/jQuery
function readMore() {
var subID = event.target.id;
var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");
alert(newTarget.id);
}
At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.
jsfiddle: https://jsfiddle.net/dr0f2nu3/
To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.
just remove the getElementsByClassName("articlePara"); in end of the newTarget .already you are call the element with id alert the element of the id is same with target.id
function readMore() {
var subID = event.target.id;
var newTarget = $('[id='+subID+'][class="articlePara"]')
console.log(newTarget.attr('id'));
console.log(newTarget.length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainContent">
<div class="articleContent">
<h1>header</h1>
<p class="articlePara" id="one"></p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">click
</div>
</div>
As you have read before, you should keep your id's unique, and you should avoid using onclick in html, but you could do it like this.
With querySelector you get the element and then with parentElement you can retrieve the parent of that element.
function readMore(el) {
var articleFooterId = el.id;
var articlePara = document.querySelector(".articleContent #"+articleFooterId);
var articleContent = articlePara.parentElement;
console.log('articleFooter', articleFooterId);
console.log('articlePara', articlePara);
console.log('articleContent', articleContent);
}
In your html you can return the 'this' object back to the function by doing readMore(this).
<div class="mainContent">
<div class="articleContent">
<h1>header1</h1>
<p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore(this)">footertext</div>
</div>
<div class="mainContent">
<div class="articleContent">
<h1>header2</h1>
<p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore(this)">footertext</div>
</div>
jsfiddle
if you're using Jquery:
$(function () {
$('div.articleFooter').click(function () {
var para = $(this).prev().find('p.articlePara').text();
alert('T:' + para);
});
})
$('.articleFooter').click(function() {
var b=subId; //can be any
var a="p[id="+b+"]"+"[class='articlePara']";
$(a).something;
});
You have forgotten to pass in event as parameter in your onclick= call in html.
In your javascript, you need to include event in the parenthesis as well.
window.readMore = function(event) {...}
if you write document.getElementById(subID).getElementsByClassName("articlePara"); That's saying you want to get your clicked element's CHILD elements that have class equal to articlePara . There is none. So you get undefined.
If you want to find all element with a ID one and a class articlePara, it can be done easily with jQuery:
newtarget = $("#one.articlePara");
You can insert a line: debugger; in your onclick handler function to trigger the browser's debugging tool and inspect the values of variables. Then you will know whether you are getting what you want.
I checked out some other posts on here but still couldn't get this issue to work.
I have several elements in my html with the class cardContainer:
<div class="cardContainer">
<div id="card2" class="block" onclick="changeClass()">
</div>
</div>
<div class="cardContainer">
<div id="card3" class="block" onclick="changeClass()">
</div>
</div>
For each onClick event I would like to call this JS function:
<script type="text/javascript">
function changeClass(){
if(document.getElementById("card2").className == "block")
document.getElementById("card2").className += " rotated";
else
document.getElementById("card2").className = "block";
}
</script>
What I would like to do is include the card3 id, so it fires the same function on click. How would I be able to combine the ids "card2" and "card3" in the javascript so the function works?
I get that if I use getElementById, I can only get one and not multiple ids/classes, but I tried using getElementsByClassName for example without success. Also looked at other posts but couldn't get this to work based on the suggestions... I am new to Javascript and not quite sure on how to approach this.
Thanks for your help!
Try this:
HTML
<div class="cardContainer">
<div class="card block">Click Here</div>
<div class="card block">Click Here</div>
<div class="card block">Click Here</div>
</div>
JavaScript
var cards = document.querySelectorAll(".card");
for (var i = 0; i < cards.length; i++) {
var card = cards[i];
card.onclick = function () {
if (this.classList.contains("block")) {
this.classList.add("rotated");
this.classList.remove("block");
}
else {
this.classList.add("block");
this.classList.remove("rotated");
}
};
}
Here is the Demo
Compatibility table for support of querySelector/querySelectorAll: Can I Use
You can pass the id of the div being clicked on your changeClass function:
<div id="card3" class="block" onclick="changeClass(this.id)">
This way, it will be easier to handle your class switching process:
function changeClass(id) {
var div = document.getElementById(id);
switch (id) {
case "card2": {
if (div.className == "className") {
div.className = "anotherClassName";
}
break;
}
case "card3": {
if (div.className == "block") {
div.className = "rotated";
}
break;
}
default: {
// any other case
}
}
}
use document.getElementsByClassName( doesn't work on ie<9 or FF<3) if you don't care about older browsers and if you do then i suggest you to use jquery, or just sizzle.js to use css selectors
I think you're looking for something like this?. (assuming you're ok with using jQuery)
http://jsfiddle.net/LqpKt/
<div class="cardContainer">
<div id="card1" class="block"></div>
</div>
<div class="cardContainer">
<div id="card2" class="block"></div>
</div>
<div class="cardContainer">
<div id="card3" class="block"></div>
</div>
<div id="output"></div>
$('.cardContainer').click(function(e){
var name = $(this).find('.block').attr('id');
$('#output').append($('<div>').html('clicked ' + name));
})