Mixing CSS & Javascript Eventhandlers - javascript

I'd like to be able to assign the same event handler to a number of different div elements. Each element will have a unique style.
I registered the eventhandler like so:
<script type="text/javascript">
function add_something() {
document.getElementById('manipulate').onclick = do_something;
}
function do_something(e) {
this.style.property = value;
}
window.onLoad = add_something;
</script>
So I can assign an event handler to an element like so:
<div id="manipulate"></div>
The problem is that I want to assign that handler to several elements, each with a unique style, and I want to use CSS to do it. but i'm not sure how to do that.
Eventually, I want something that looks like this:
<style>
#element1{...}
#element1{...}
#element1{...}
</style>
.....
<div id="element1" class="manipulate"></div>
<div id="element2" class="manipulate"></div>
<div id="element3" class="manipulate"></div>
Is this possible? Thanks

Event delegation?
HTML:
<div id="wrap">
<div id="element1" class="manipulate">First element</div>
<div id="element2" class="manipulate">Second element</div>
<div id="element3" class="manipulate">Third element</div>
</div>
JavaScript:
var wrap = document.getElementById('wrap');
wrap.onclick = function (e) {
var elem = e.target;
elem.style.color = 'red';
};
Live demo: http://jsfiddle.net/VLcPw/

You can select elements by class in modern browsers, or just use jQuery and know it works everywhere.
$(document).ready(function(){
$('.manipulate').click(function(){alert('Hello.')});
//or .hover/any other event.
});
jQuery events.
Perhaps a more relevant example?
$('.manipulate').click(function(){
$(this).addClass( 'whateverClass' );
//or
$(this).css('color', 'red');
});

Why are you not giving jquery a try?
With jquery you should just need this to bind the same click event to all corresponding elements:
$("div.manipulate").click(function(e) {
$(this).css(property, value);
});
property has to replaced with a valid css property, value with a correct value, of course.

Related

Use variable as selector in function

On click, I want to get the name of the closest div and then look for all div's, that have this name attribute and add a class to them.
Here is my code:
HTML:
<div class="wrapper">
<div class="container" name="button1">
<div class="button">this is p #1</div>
</div>
</div>
<div name="button1">
somewhere else
</div>
JS:
$('.wrapper').on("click", '.button', function() {
var attrname = $(this).closest('.container').attr('name');
$("div[name=attrname]").each(function() {
$(this).addClass("classtobeadded");
});
});
But it is not working. So, how can I use the variable in here:
$("div[name=attrname]").each(function()
Here is the fiddle:
There's a few issues with your logic. Firstly the .container element does not have the name attribute, the .button does, so you don't need to use closest(). Secondly, you need to concatenate the actual name value in to the selector. Lastly div elements do not have a name attribute so the HTML is invalid. If you want to store custom meta-data on an element use a data attribute instead.
Also note that you don't need the each() loop, you can just call addClass() on the collection selected with the data-name attribute. Try this:
$('.wrapper').on("click", '.button', function() {
var attrname = $(this).data('name');
$('div[data-name="' + attrname + '"]').addClass("classtobeadded");
});
.classtobeadded {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="button" data-name="button1">this is p #1</div>
</div>
</div>
<div data-name="button1">
somewhere else
</div>
You have to concatenate it properly,
$(`div[name=${attrname}]`).each(function() {
And by the way, when looking at your code there is no attribute available in the closest div with a class .container. Check that as well.
$("div[name=" + attrname + "]").each(function() {})
or
$(`div[name=${attrname}]`).each(function() {})

How to make a re-usable element with $(this) triggers the clicked element only

I'm trying to make my JS logic to use the $(this) so I can re-use my code in multiple elements in the same page so that they are each triggered individually.
this is my JS code:
$(".fab").on("click", function(){
$(this).toggleClass("clicked");
$(".screen2").addClass("active");
$(".box2 ,.box1 ,.box3").addClass("active");
});
$("#close").on("click", function(){
$(".screen2").removeClass("active");
$(".fab").removeClass("clicked");
$(".box1 ,.box2 ,.box3").removeClass("active");
});
My HTML:
<div class="app">
<div class="header"></div>
<div class="content">
<h1>Click the fab</h1>
</div>
<div class="fab"></div>
<div class="screen2">
<h1>new window</h1>
<div id="close"></div>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
</div>
how can I use properly the $(this) ? All I'm trying to do is to make that JS code re-usable for multiple elements in the same page so that it triggers ONLY for the element where I clicked the .fab button...
You also need to use $(this), .prev(), .next(), .find(), .closest() etc. to traverse the DOM to refer to the elements near the one you're working on, otherwise it will target all of the classes in your document.
$(".fab").on("click", function(){
$(this).toggleClass("clicked");
$(this).next(".screen2").addClass("active");
$(this).next(".screen2").find(".box2 ,.box1 ,.box3").addClass("active");
});
$("#close").on("click", function(){
$(this).closest(".screen2").removeClass("active");
$(this).closest(".screen2").prev(".fab").removeClass("clicked");
$(this).closest(".screen2").find(".box1 ,.box2 ,.box3").removeClass("active");
});
You can store the jQuery selectors in an array, iterate through it, and for each jQuery selector in the array, use jQuery's .each() to iterate through its inner elements.
In the following example, there may be multiple instances of class1 in the DOM, for example.
var arrElements = [$('#id1'), $('#id2'), $('.class1')];
for (var i = 0; i < arrElements.length; i++) {
arrElements[i].each(function() {
$(this).on('click', function() {
// do stuff (use $(this) to refer to the current object)
});
})
}

How could i target a div and it's child to handle a click?

I have a <div class="stock"></div>wrapped around :
<div class="stockAdd"></div>
<div class="stockRemove"></div>
<div class="stockInput"></div>
I want to prevent a click inside my .stock to trigger a function. For now i have the following :
if ($(event.target).is('.stockInput') || $(event.target).is('.stockAdd') || $(event.target).is('.stockRemove')) {
console.log("Ajout stock");
return
}
Isn't there a better way to select thos three divs ? The $(event.target).is('.stock') don't get the job done when i click my nested divs.
Thanks
If I understand you correctly, you want to catch click events on .stockAdd, .stockRemove, and .stockInput, but not on other elements within .stock itself, is that correct?
If so, a delegated event can take care of that without any need to manually check the event target:
$('.stock').on('click', '.stockAdd, .stockRemove, .stockInput', function() {
alert("Clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stock">
<div class="stockAdd">stockAdd</div>
<div class="stockRemove">stockRemove</div>
<div class="stockInput">stockInput</div>
<div>No event</div>
</div>
I would strongly recommend against depending on event.target here; it's too fragile. Any HTML tags nested inside your desired targets would break things:
$('.stock').on('click', function(event) {
if (event.target.className=="stockAll") {
alert("clicked");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stock">
<div class="stockAll">
This <b> will not work if someone clicks in the bold area</b> but works outside
</div>
</div>
You can add a separate class to all of them like .stock-inner and then grab them all with $('.stock-inner') or you can use a $("div[class^='stock-inner']) - this will grab the parent .stock div...
Also, to reject a click event within the handler you're gunna want to use e.preventDefault() where e is the event object.
the reason it doesn't work well on nested divs is they pass the conditional if in your example, to make it stricter you could add div to selector:
if ($(event.target).is('div.stockInput') || $(event.target).is('div.stockAdd') || $(event.target).is('div.stockRemove'))
You can attach the event on .stock and then filter using the event.target.
HTML
<div class="stock" style="border: 10px solid #000;">
<div class="stockAdd">Add</div>
<div class="stockRemove">Remove</div>
<div class="stockInput">Input</div>
</div>
JavaScript
$('.stock').on('click', function(e) {
if( e.target.className !== 'stock' ) {
console.log(e.target.className);
}
});
jsfiddle

copy text from one div to other div using javascript

<div id="noty">Hello</div>
<div id="noty">World</div>
<div id="noty">Nation</div>
<div id="textArea"></div>
$("#noty").click(function() {
$("#textArea").html($("#noty").html());
});
I'm using this to copy text from one div to other by onclick function. But this is not working. It's only working on the first div. Is there any way to accomplish this ?
Use something like this:
<div class="noty">Hello</div>
<div class="noty">World</div>
<div class="noty">Nation</div>
<div id="textArea"></div>
<script>
$(".noty").click(function() {
$("#textArea").html($(this).html());
});
</script>
https://jsbin.com/giqilicesa/edit?html,js,output
Like this.
$(".noty").click(function(e) {
$("#textArea").html(e.target.innerHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="noty">Hello</div>
<div class="noty">World</div>
<div class="noty">Nation</div>
<div id="textArea"></div>
Yes. var s = ''; $('.noty').each(function () {s += $(this).html();}); $('#textarea').html(s); but change your divs to use class="noty" instead of id. The id should be unique.
At first, you must not use multiple id attribute. And another problem is sizzle providing jQuery as a selector engine returns result to use getElementById. It means even if you've declared multiple ids, you'll get just only one id element. When consider those problems, you can get over this problem to follow this way:
<div class="noty">Hello</div>
<div class="noty">World</div>
<div class="noty">Nation</div>
<div id="textArea"></div>
<script>
var $noty = $('.noty');
var $textarea = $('#textArea');
$noty.click(function () {
var text = Array.prototype.map.call($noty, function (el) {
return $(el).html();
}).join(' ');
$textarea.html(text);
});
</script>

Jquery - Adding event to specific div that shares class name with others

I'm looking to add a mouseup event to a series of divs, that when clicked, reveal a child div ('menu'). All the parent divs share the same class, for example:
<div class="container">
<div class="menu"><p>Text</p></div>
</div>
<div class="container">
<div class="menu"><p>Text</p></div>
</div>
etc...
However, I'd like the event to only trigger when I've clicked that particular 'container'. When I click on another 'container', I'd like the same thing to happen, however, I'd also like the previously opened 'menu' to hide. The only way I have managed to do this (being a JQuery noob), is to create variables for each container, as well as giving them unique classes. For example:
$(document).mouseup (function (e){
var buttonOne = $(".containerOne");
var buttonTwo = $(".containerTwo");
var menuOne = $(".containerOne").find(".menu");
var menuTwo = $(".containerTwo").find(".menu");
if(buttonOne.is(e.target)){
menuOne.toggle(100);
menuTwo.hide();
}
else if(buttonTwo.is(e.target)){
menuTwo.toggle(100);
menuOne.hide();
}
else {
$(".menu").hide();
}
});
Quick JSFiddle
This then creates lines and lines of code the more containers I add, and I feel there is almost certainly an easier way of doing this. Apologies if this was written poorly, it's been a long day, ha.
Add a new class to the containerxxx element then use a simple click handler
<div class="containerOne container">
<div class="menu">
<p>Text</p>
</div>
</div>
<div class="containerTwo container">
<div class="menu">
<p>Text</p>
</div>
</div>
then
var $menus = $('.container .menu');
$('.container').mouseup(function (e) {
var $menu = $(this).find('.menu').toggle();
$menus.not($menu).hide()
});
Demo: Fiddle
How about something like
$(".container").on("click", function() {
var mine = $(".menu", this).toggle(100);
$(".menu").not(mine).hide();
});

Categories

Resources