I create multiple div's dynamically with Javascript
var cart = document.createElement("div");
cart.classList.add("buy-item");
cart.setAttribute("name", "buy-food");
div.appendChild(cart);
and when i collect all the elements with the "buy-item" class i get the elements as an HTMLCollection but when i want to know when it was clicked nothing happens
var elements = document.getElementsByClassName("buy-item");
console.log(elements)
function addFoodToCart() {
console.log("One of buy-item class itemes was clicked")
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', addFoodToCart);
}
The HTML element looks like this
<div class="food-wrap dynamic-food">
<img class="food-item-img" src="/img/foodItem.png">
<p class="food-title">Csípős</p><p class="food-price">190</p>
<div class="buy-item" name="buy-food"></div>
<div class="tooltip">
<span class="tooltiptext">Csípős szósz</span>
</div>
</div>
tl;dr: Add the event listener to the parent div (the one holding all the other elements that you have/will be creating) and use event.target to know which one was clicked.
Not sure if this helps and if this is your case, but you could be benefited by the understanding of Event Bubbling and Event Delegation in Javascript.
In my example below, run the code and click in each paragraph. The console log will show which element you cliked.
function findTheOneClicked(event) {
console.log(event.target)
}
const mainDiv = document.getElementById("parent");
mainDiv.addEventListener('click', findTheOneClicked);
<div id="parent">
<p>"Test 1"</p>
<p>"Test 2"</p>
<p>"Test 3"</p>
</div>
This is really good when you have an element with many other elements on it and you want to do something with them, or when you want to add an event handler to an element that is not available (not created yet) on your page.
Good reading on this topic:
https://javascript.info/bubbling-and-capturing
I am attempting to use the following javascript to create various popups.Image popups when text is clicked. The problem is that when I click any of the text containers, all of the popup images appear. I know I am missing something obvious. Any help would be much appreciated. Here is the JS code:
function myFunction() {
var popup = document.getElementsByClassName("myPopup");
for(var i=0; i<popup.length; i++) {
popup[i].classList.toggle('show');
}
}
HTML:
<div class="popup" onclick="myFunction()"><span class="castName">Viola,</span>
<span class="popuptext myPopup"><img src=Viola_1.jpg
style="width:300px;height:100%;" alt="Viola"><p>Miss Ellen Terry as Viola, mid
to late 19th century</p></span></div>
Your function gets a list of elements and toggle the class 'show' to every element instead of the element you want. You have to pass in the element to the function.
You can change the onclick event for each div from:
<div class="popup" onclick="myFunction()">
to:
<div class="popup" onclick="myFunction(this)">
Then in your javascript
function myFunction(element){
if (element){ //If the element is passed into this function
element.getElementsByClassName("myPopup")[0].toggle('show');
}
}
Thum, this was very helpful. I ended up changing the HTML as you suggested and did the following to the javascript, which worked perfectly:
function myFunction(element) {
var popup = element.getElementsByClassName('myPopup');
var i;
for( i=0; i<popup.length; i--) {
popup[i].classList.toggle('show');
}
}
I've just started learn JavaScript and wanted to try something.
How can I make JavaScript function work on other function? Like, I want when you click on a div, other div will have background-color:yellow; (or x.style.backgroundColor="yellow"; in JS), like this:
<div onclick="yellow">Click me to paint the other div in yellow</div>
<div id="painted">I should be painted yellow if you click the above div!</div>
In C-language I know it can be possible if you call recursion so I tried use it though I don't know.
Of course it didn't succeed but there's a jsbin if you want to look.Q: How can I paint a div in yellow background with other div function using JavaScript?
Thanks in advance.
You will have to attach the function with parenthesis like fillYellow(),
<div onclick="fillYellow()">Click me to paint the other div in yellow</div>
<div id="painted">I should be painted yellow if you click the above div!</div>
<script>
function fillYellow(){
document.getElementById('painted').style.background = "yellow";
}
</script>
Inside this function get the painted div by it's id and apply background color for this div.
You should have document.getElementById("backgroundChange"); instead of getElementById("backgroundChange"); and it will work :)
As your question was "How can I make JavaScript function work on other function?" I started to think maybe you're really talking about doing something event-driven.
Therefore, why not consider this (slightly more advanced) solution
When you click a <div>, you fire a custom "paint" event at every <div>.
The event fired at itself is different to at other <div>s.
When a <div> node sees a "paint" event e, it applies e.style to node.style
The code would look like this
function paintEvent(style) { // function make a custom event
var ev = new Event('paint');
ev.style = style;
return ev;
}
function applyPaint(node, style) { // function to style a node
var key;
for (key in style) { // loop over object
node.style[key] = style[key];
}
}
function paintHandler(e) { // function to fire when you see a "paint" event
applyPaint(this, e.style);
}
function clickHandler(e) { // function to fire when you see a "click" event
var divs = document.getElementsByTagName('div'),
i,
paint = paintEvent({'background-color': 'yellow'});
this.dispatchEvent(paintEvent({'background-color': 'red'}));
for (i = 0; i < divs.length; ++i) { // loop over array-like
if (divs[i] !== this)
divs[i].dispatchEvent(paint);
}
}
window.addEventListener('load', function () { // when the Window has loaded
var divs = document.getElementsByTagName('div'),
i;
for (i = 0; i < divs.length; ++i) { // loop over array-like
divs[i].addEventListener('click', clickHandler); // attach the handlers
divs[i].addEventListener('paint', paintHandler);
}
});
DEMO
Your yellow event handler should look up the div with the id "painted" and then add a class to it which will give it yellow text.
This is one way ( a simple one) but where are a number of other similar ways to accomplish this.
I want to register for events on a button in a web page using javascript addEventListener or something equivalent. But the web page doesn't appear to have standard form buttons. The html snippet below is the html markup for what appears as a button on the page.
I want to detect mousedown (or mouseclick or equiv). Is there any way I could detect the user clicking on this button?
<a href="javascript:" id="WIN_0_536870914" arid=536870914 artype="Control" ardbn="Dial" artcolor="null" class="btn btn3d arfid536870914 ardbnDial" style="top:247; left:115; width:46; height:21;z-index:1001;">
<div class="btntextdiv" style="top:0; left:0; width:46; height:21;">
<div class="f1" style=";width:46">Dial</div>
</div>
</a>
The only tricky bit will be getting the elements from the DOM in the first place. If you know the id then it's trivial to get this specific button:
var elem = document.getElementById('WIN_0_536870914');
elem.addEventListener('click', function () {
alert('click!');
});
http://jsfiddle.net/ugsYB/
Although you probably want to target all the buttons by their class:
var elems = document.getElementsByClassName('btn');
var i;
for(i = 0; i < elems.length; i++) {
var elem = elems[i];
elem.addEventListener('click', function () {
alert('click!');
});
}
http://jsfiddle.net/ugsYB/1/ (Note: there are cross browser issues with getElementByClassName)
Of course, jQuery makes this sort of thing trivial:
$('.btn').click(function () { alert('click!'); });
http://jsfiddle.net/ugsYB/2/
But it might be overkill for your needs.
I just created script that shows/hides (toggles) block of HTML. There are four buttons that each can toggle its HTML block. When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button... it hides that HTML block and shows new one.
Here is what I have at the moment:
$('.btn_add_event').click( function() {
$('.block_link, .block_photos, .block_videos').hide();
$('.block_event').toggle();
});
$('.btn_add_link').click( function() {
$('.block_event, .block_photos, .block_videos').hide();
$('.block_link').toggle();
});
$('.btn_add_photos').click( function() {
$('.block_event, .block_link, .block_videos').hide();
$('.block_photos').toggle();
});
$('.btn_add_videos').click( function() {
$('.block_event, .block_link, .block_photos').hide();
$('.block_videos').toggle();
});
Any ideas how to reduce code size? Also, this script isn't very flexible. Imagine to add two new buttons and blocks.
like Sam said, I would use a class that all the blocks share, so you never have to alter that code. Secondly, you can try 'traversing' to the closest block, therefore avoiding it's name. That approach is better than hard coding each specific block, but if the html dom tree changes you will need to refactor. Last, but best, you can pass in the class name desired block as a variable to the function. Below is something you can copy paste that is close to what you started with.
$('.myAddButtonClass').click( function() {
$('.mySharedBlockClass').filter(':visible').hide();
//find a good way to 'traverse' to your desired block, or name it specifically for now.
//$(this).closest(".mySharedBlockClass").show() complete guess
$('.specificBlockClass').show();
});
I kept reading this "When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button" thinking that my eyes were failing me when Its just bad English.
If you want to make it more dynamic, what you can do is add a common class keyword. Then
when the click event is raise. You can have it loop though all the classes that have the
keyword and have it hide them all (except the current one that was clicked) and then show the current one by using the 'this' keyword.
you can refer below link,
http://chandreshmaheshwari.wordpress.com/2011/05/24/show-hide-div-content-using-jquery/
call function showSlidingDiv() onclick event and pass your button class dynamically.
This may be useful.
Thanks.
try this
$('input[type=button]').click( function() {
$('div[class^=block]').hide(); // I resumed html block is div
$(this).toggle();
});
Unfortunatly I couldn't test it, but if I can remember right following should work:
function toogleFunc(clickObject, toogleTarget, hideTarget)
{
$(clickObject).click(function()
{
$(hideTarget).hide();
$(toogleTarget).toggle();
});
}
And the call:
toogleFunc(
".btn_add_videos",
".block_videos",
".block_event, .block_link, .block_photos"
);
and so far
Assuming the buttons will only have one class each, something like this ought to work.
var classNames = [ 'btn_add_event', 'block_link', 'block_photos', 'block_videos' ];
var all = '.' + classNames.join(', .'); // generate a jquery format string for selection
$(all).click( function() {
var j = classNames.length;
while(j--){
if( this.className === classNames[j] ){
var others = classNames.splice(j, 1); // should leave all classes but the one on this button
$('.' + others.join(', .')).hide();
$('.' + classNames[j]).toggle();
}
}
}
All the buttons have the same handler. When the handler fires, it checks the sender for one of the classes in the list. If a class is found, it generates a jquery selection string from the remaining classes and hides them, and toggles the one found. You may have to do some checking to make sure the strings are generating correctly.
It depends by how your HTML is structured.
Supposing you've something like this
<div class="area">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
...
<div class="sender">
<a class="one"></a>
<a class="two"></a>
<a class="three"></a>
</div>
You have a class shared by the sender and the target.
Your js would be like this:
$('.sender > a').click(function() {
var target = $(this).attr('class');
$('.area > .' + target).show().siblings().hide();
});
You show your real target and hide its siblings, which aren't needed.
If you put the class postfixes in an array, you can easily make this code more dynamic. This code assumed that it doesn't matter in which order toggle or hide are called. If it does matter, you can just remember the right classname inside the (inner) loop, and toggle that class after the loop.
The advantage to this approach is that you can extend the array with an exta class without needing to modifying the rest of the code.
var classes = new Array('videos', 'event', 'link', 'photos');
for (var i = 0; i < classes.length; ++i)
{
$('.btn_add_' + classes[i]).click(
function()
{
for (var j = 0; j < classes.length; ++j)
{
if (this.hasClass('btn_add_' + classes[j]))
{
$('.block_' + classes[j]).toggle();
}
else
{
$('.block_' + classes[j]).hide();
}
}
});
}
You could make this code more elegant by not assigning those elements classes like btn_add_event, but give them two classes: btn_add and event, or even resort to giving them id's. My solution is based on your description of your current html.
Here is what I think is a nice flexible and performant function. It assumes you can contain your links and html blocks in a parent, but otherwise it uses closures to precalculate the elements involved, so a click is super-fast.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" ></script>
<script type="text/javascript">
// Enables show/hide functionality on click.
// The elements within 'container' matching the selector 'blocks' are hidden
// When elements within 'container' matching the selector 'clicker' are clicked
// their attribute with the name 'clickerAttr' is appended to the selector
// 'subject' to identify a target, usually one of the 'blocks'. All blocks
// except the target are hidden. The target is shown.
//
// Change clickerAttr from 'linkTarget' to 'id' if you want XHTML compliance
//
// container: grouping of related elements for which to enable this functionality
// clicker: selector to element type that when clicked triggers the show/hide functionality
// clickerAttr: name of the DOM attribute that will be used to adapt the 'subject' selector
// blocks: selector to the html blocks that will be shown or hidden when the clicker is clicked
// subject: root of the selector to be used to identify the one html block to be shown
//
function initToggle(container,clicker,clickerAttr,blocks,subject) {
$(container).each(
function(idx,instance) {
var containerElement = $(instance);
var containedBlocks = containerElement.find(blocks);
containerElement.find(clicker).each(function(idxC, instanceClicker) {
var tgtE = containerElement.find(subject+instanceClicker.getAttribute(clickerAttr));
var clickerBlocks = containedBlocks.not(tgtE);
$(instanceClicker).click(function(event) {
clickerBlocks.hide();
tgtE.toggle();
});
});
// initially cleared
containedBlocks.hide();
}
);
}
$(function() {
initToggle('.toggle','a.link','linkTarget','div.block','div.');
});
</script>
</head>
<body>
Example HTML block toggle:
<div class="toggle">
a <br />
b <br />
c <br />
<div class="A block"> A </div>
<div class="B block"> B </div>
<div class="C block"> C </div>
</div> <!-- toggle -->
This next one is not enabled, to show scoping.
<div class="toggle2">
a <br />
<div class="A block">A</div>
</div> <!-- toggle2 -->
This next one is enabled, to show use in multiple positions on a page, such as in a portlet library.
<div class="toggle">
a <br />
<div class="A block">A</div>
</div> <!-- toggle (2) -->
</body>
</html>