Click event and for loop - javascript

HTML code:
<div class="test" id="inner1">
ONE
</div>
<div class="test" id="inner2">
TWO
</div>
<div class="test" id="inner3">
THREE
</div>
<div class="test1" id="outer1">
ONE
</div>
<div class="test1" id="outer2">
TWO
</div>
<div class="test1" id="outer3">
THREE
</div>
Javascript code:
<script type="text/javascript">
for (var i=1;i<=3;i++)
{
$("#inner"+i).click(function () {
$("#outer"+i).css("background-color","blue")
});
}
</script>
and the CSS:
.test{
width: 100px;
padding: 10px;
background-color: green;
margin-bottom:10px;
cursor:pointer;
}
.test1{
width: 100px;
padding: 10px;
background-color: red;
margin-bottom:10px;
}
What I want is to change background color of outer1 by clicking on inner1, change background color of outer2 by clicking on inner2 and change background color of outer3 by clicking on inner3. The above code does not work since it looks for outer4 (i=4) which does not exist when event click is triggered... Do you have any idea how to implement the above with some kind of loop?
Thank you
http://jsfiddle.net/Lpwmyspo/1/

When you iterate like that, the i inside the click function isn't evaluated until you actually click something, and at that time the loop has finished and the value of i is the last thing it was set to in the loop.
The real question is why you're using a loop to begin with when you can use the attribute-starts-with selector and this instead
$('[id^="inner"]').on('click', function () {
$('#outer' + this.id.slice(-1)).css("background-color","blue");
});
FIDDLE

How about?
$(".test").on("click", function() {
var which = this.id.replace(/^inner/, "outer");
$(".test1").css("background-color","transparent"); // in case you need to reset the background
$("#" + which).css("background-color","blue");
});
Demo#Fiddle

Do it in the following way:
<div class="test" id="inner1" onclick="abc(this)">
ONE
</div>
<div class="test" id="inner2" onclick="abc(this)">
TWO
</div>
<div class="test" id="inner3" onclick="abc(this)">
THREE
</div>
<div class="test1" id="outer1">
ONE
</div>
<div class="test1" id="outer2">
TWO
</div>
<div class="test1" id="outer3">
THREE
</div>
and the JavaScript part as follows:
<script type="text/javascript">
function abc(e){
var id = e.id;
var lastchar = id.substr(id.length -1);
document.getElementById("outer"+lastchar).style.backgroundColor='blue';
}
</script>

Related

How to get the element that was used as event selector

I got the following problem.
I got an div with is filled with different elements and that has a mouserover-event. I need to use the div in the mouseover-function. The Problem is that i can't select the div via it's class because there are many automaticaly created divs with the same class.
I have tryed to use event.targetbut it returns the object that is inside the that that was used as selector.
$(".outer").on("mouseover",function(event){
alert("event.target.className is: " + event.target.className);
});
.inner{
background-color:#ccc;
min-width:100px;
width:100%;
min-height:100px;
height:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class= "outer">
<div class="inner">
here
</div>
</div>
Is there any way to get the div outer on mouseover without selecting it by it's class?
I also can't just use $(event.target).parent() because there can be deeper nested structures inside the outer div that are dynamically created
The way I understood the question is you really want to use mouseover event on the .inner div(s). With the example you provided, what would happen if .outer div had padding for example? The event would still trigger even though we are not hovering over .inner div at all. So I would change the event attaching a little and use jQuerys .closest-method to travel back up to the parent div:
var $container = $(".outer");
$container.on("mouseover", ".inner", function(event) {
console.log($(this).closest(".outer").attr("class"));
// or since in this case you know it's the same element:
// console.log($container.attr("class"));
});
.outer {
padding-top: 30px;
background: Red;
}
.inner {
background-color: #ccc;
min-width: 100px;
width: 100%;
min-height: 100px;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
<div class="inner">
here
</div>
<div class="inner">
here 2
</div>
</div>
Hope, this would work for you:
$(".outer").on("mouseover",function(event){
alert("event.target.className is: " + $(event.target).parent().attr('class'));
});
.inner{
background-color:#ccc;
min-width:100px;
width:100%;
min-height:100px;
height:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class= "outer">
<div class="inner">
here
</div>
</div>
Use this instade of event.target
this trigger current selector.
$(".outer").on("mouseover",function(event){
alert("event.target.className is: " + this.className);
});
Like this?
I don't understant why you can't use parent
Well, you can get the current listener object just by using "this"
$(".outer").on("mouseover", function(event){
var obj = $(this);
console.log(obj.hasClass("outer"))
});
.inner{
background-color:#ccc;
width:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
<div class="inner">
here
</div>
</div>
<div class="outer">
<div class="inner">
<div>
<div>
<div>
<div class="someclass">
<div>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
deeeeeeeep inside
</div>
</div>
</div>
</div>
</div>
there
</div>
</div>
Have you tried event.currentTarget
Example: http://codepen.io/camtullos/pen/bgQNoa?editors=1111
$(".outer").on("mouseover",function(event){
console.log(event.currentTarget.className);
});

Javascritpt change class to a div near to his grand-father

I want to dynamically change the class of the element #sidePanel from .compact to .expanded, in this code:
<div id="sidePanel" class="compact"></div>
<div id="topbar">
<div id="buttonContainer">
<div id="button"></div>
</div>
</div>
I'm stuck here, I can't apply the class to the correct <div>, I can just add the class to the topbar:
$(document).ready(function(){
$("#button").mouseover(function(){
$("this").parent().eq(2).addClass(".expanded").removeClass(".compact");
});
});
I also tried this:
$(document).ready(function(){
$("#button").mouseover(function(){
$("#sidepanel").addClass(".expanded").removeClass(".compact");
});
});
Your second example was pretty close. When you $.addClass() and $.removeClass(), or are referring to classnames outside of using a selector to target something, just reference the class name (no need for the leading .). Also JS (and CSS) are case-sensitive, so $('#sidepanel') won't target #sidePanel - the cases need to match.
$("#button").mouseover(function() {
$("#sidePanel").addClass("expanded").removeClass("compact");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>.expanded {color: red;}</style>
<div id="sidePanel" class="compact">sidepanel</div>
<div id="topbar">
<div id="buttonContainer">
<div id="button">button</div>
</div>
</div>
In your first example, $(this) is how you reference this in jQuery. If you put this in quotes, the word this is treated as a string literal instead. And since to use $.parent() you would need to go up 2 levels, you should use $.parents() with the ID of the parent you want to target, then use $.prev() to select the previous element, which is #sidePanel. So to traverse the DOM like that, this is how I would do it.
$("#button").mouseover(function() {
$(this).parents('#topbar').prev().removeClass('compact').addClass('expanded');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>.expanded {color: red;}</style>
<div id="sidePanel" class="compact">sidepanel</div>
<div id="topbar">
<div id="buttonContainer">
<div id="button">button</div>
</div>
</div>
Your problem is you used $("#sidepanel") instead of $("#sidePanel")
Here's a working example after the change is made:
$(document).ready(function(){
$("#button").on('mouseover', function(){
$("#sidePanel").addClass("expanded").removeClass("compact");
});
});
#topbar > div {
width: 100px;
height: 30px;
background: #ccc;
margin-top: 20px;
}
#sidePanel {
width: 100%;
height: 40px;
background: #ccc;
}
#sidePanel.expanded {
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sidePanel" class="compact"></div>
<div id="topbar">
<div id="buttonContainer"></div>
<div id="button"></div>
</div>
first: the solution
$(document).ready(function()
{
$("#button").mouseover(function()
{
// class names - without the dot
$("#sidepanel").addClass("expanded").removeClass("compact");
});
});
then: why you were really close on your first attempt
$(document).ready(function()
{
$("#button").mouseover(function()
{
// $(this) selector uses the `this` keyword (not as a string)
$(this).parent().eq(2).addClass(".expanded").removeClass(".compact");
});
});

Closing all other DIVS while opening one

What I am trying to achieve is the following
There are two DIVS with dropdown. I need to close one while opening the other on click function.
I am also trying to mouseout once the event is out of the dropdown box.
I would like to close the DIV once the click even happens outside the dropdown box.
Following is the HTML
<div class="first-div" style="display:inline-block">
<a class="first-div-link"><h6>REGION</h6></a>
<div class="first-div-dropdown">
<p>Drop down test from first DIV</p>
</div>
</div>
<div id="second-div" style="display:inline-block; float:right">
<h6>REGISTER</h6>
<div class="second-div-dropdown">
<p>Drop down test from second DIV</p>
</div>
</div>
CSS is following
.first-div-dropdown, .second-div-dropdown{
background-color:#555;
color:white;
height:100px;
width:200px;
}
JS is following
$(document).ready(function(){
$('.first-div-dropdown').hide();
$('.second-div-dropdown').hide();
$('.first-div-link').on('click', function (event){
$('.first-div-dropdown').slideDown(300);
});
$('.second-div-link').on('click', function (event){
$('.second-div-dropdown').slideDown(300);
});
});
Is there any way to use this as a function to control multiple DOMs in the HTML? If so could someone assist me with the current example ?
Thanks
The path to follow here is use a common class on your items, you don't need to create new classnames if all will have the same styles and will perform the same action. Check this:
$(document).ready(function() {
$('.cont-div').on('click', 'a', function(e) {
e.preventDefault();
$('.div-dropdown').slideUp(300);
$(this).next('.div-dropdown').stop().slideToggle(300);
});
//To close if you click outside the container divs
$('body').on('click', function(e) {
if (!$(e.target).parents('.cont-div').length) {
$('.div-dropdown').slideUp(300);
}
})
});
body {
height: 600px;
background: #e1e1e1;
}
.cont-div {
display: inline-block;
vertical-align: top;
width: 50%;
}
.div-dropdown {
background-color: #555;
color: white;
height: 100px;
width: 200px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont-div">
<h6>REGION</h6>
<div class="div-dropdown">
<p>Drop down test from first DIV</p>
</div>
</div><!--
--><div class="cont-div">
<h6>REGISTER</h6>
<div class="div-dropdown">
<p>Drop down test from second DIV</p>
</div>
</div>
If you want to get more specific, you could assign a similar class to both menus, in the case below, I added 'dropdown-div' to the class for both menus and then simply added a trigger whenever you click on something that is not a link, it will hide the menus by calling $('.dropdown-div').hide();
$(document).ready(function(){
$('.first-div-dropdown').hide();
$('.second-div-dropdown').hide();
$('.first-div-link').on('click', function (event){
$('.first-div-dropdown').slideDown(300);
});
$('.second-div-link').on('click', function (event){
$('.second-div-dropdown').slideDown(300);
});
});
$(document).on('click', function(event) {
if (!$(event.target).closest('a').length) {
$(".dropdown-div").hide();
}
});
.first-div-dropdown, .second-div-dropdown{
background-color:#555;
color:white;
height:100px;
width:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="first-div " style="display:inline-block">
<a class="first-div-link"><h6>REGION</h6></a>
<div class="first-div-dropdown dropdown-div">
<p>Drop down test from first DIV</p>
</div>
</div>
<div id="second-div" style="display:inline-block; float:right">
<h6>REGISTER</h6>
<div class="second-div-dropdown dropdown-div">
<p>Drop down test from second DIV</p>
</div>
</div>
You're dealing with state management within a collection. You have 2 dropdowns, but 3 states: dropdown one's state, dropdown two's state, and the collection of dropdowns' state.
Using jQuery, the most common way of handling this I've seen is to start by "resetting" the collection's state each time, by hiding all dropdowns on click.
Then, open the dropdown that is being targeted by the client. This can also be a bit easier if you use a single class to target the collection which also lends itself to be reusable across an infinite number of dropdowns.
<div class="first-div" style="display:inline-block">
<a class="dropdown-trigger"><h6>REGION</h6></a>
<div class="dropdown-menu">
<p>Drop down test from first DIV</p>
</div>
</div>
<div id="second-div" style="display:inline-block; float:right">
<a class="dropdown-trigger"><h6>REGION</h6></a>
<div class="dropdown-menu">
<p>Drop down test from second DIV</p>
</div>
</div>
JS:
$('.dropdown-trigger').click(function (event) {
event.stopPropagation();
var $menu = $(this).siblings('.dropdown-menu');
$('.dropdown-menu').not($menu).slideUp(300);
$menu.slideToggle(300);
});
$(document).click(closeDropdowns);
function closeDropdowns () {
$('.dropdown-menu').slideUp(300);
}
Working codepen: http://codepen.io/amishstripclub/pen/wzbEVo
You could try using toggle like this:
$(document).ready(function(){
$('.first-div-link').on('click', function (event){
$('.first-div-dropdown').toggle();
$('.second-div-dropdown').toggle();
});
$('.second-div-link').on('click', function (event){
$('.first-div-dropdown').toggle();
$('.second-div-dropdown').toggle();
});
});

Run JS by clicking a div element

Im working on a website that has a few different colored boxes made with divs, and I want to use them to open certain things. Whether it be music, photos, etc. Im using JS to generate a random number and use the number to choose which song to open, but I have no clue how to attach it to the div itself.
</head>
<body style="background-color:#FFF;">
<div id="center">
<div id="header">
<div id="title"><h1>welcom3 :-)</h1></div>
<div id="wrapper">
<div id="redbox">
</div>
<div id="6box">
</div>
<div id="bluebox">
</div>
<div id="greenbox">
</div>
<div id="yellowbox">
</div>
<div id="yellowboxmargin">
</div>
<div id="yellowboxmargin">
</div>
<div id="yellowboxmargin">
</div>
</div>
</div>
</body>
</html>
use jQuery
<div id="box1"></div>
<script>
$(document).ready(function() {
$("#box1").click(function(){
yourfunc();
}
})
</script>
If you need run js code without jquery, use this example.
In head:
<script>
function hello() {
// do something
}
</script>
In body:
<div onclick="hello()">Hello</div>
I would follow the advice of Buddhi Abeyratne and use jQuery. Of course, this is just a guess, but I would say that due to the nature of your project, it will make things easier for you.
jQuery has different methods to attach events to an alement. In this case, you can use the shortcut ".click()".
I leave you here a snippet:
function do_something_cool(box)
{
alert("I have code to make something awesome with " + box.attr("id"));
}
$(document).ready(function()
{
$("#wrapper div").click(function() { do_something_cool($(this)); });
});
body
{
background-color: #FFF;
}
.colored_box
{
height: 50px;
width: 50px;
margin: 5px;
}
#redbox
{
background-color: red;
}
#bluebox
{
background-color: blue;
}
#greenbox
{
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="center">
<div id="header">
<div id="title"><h1>welcom3 :-)</h1></div>
<div id="wrapper">
<div id="redbox" class="colored_box"></div>
<div id="bluebox" class="colored_box"></div>
<div id="greenbox" class="colored_box"></div>
</div>
</div>
</div>
</body>
But if you decide to don't use jQuery, here you have the vanilla javascript:
window.onload = function()
{
var boxes = document.getElementById("wrapper").getElementsByTagName("div");
for (var i = 0; i < boxes.length; i++)
{
boxes[i].addEventListener("click", do_something_cool);
}
}
function do_something_cool(evt)
{
alert("I have code to make something awesome with " + evt.target.id);
}
Btw, I guess it is just a copy/paste thing, but you forgot to close one div.
Also, pay attention to how I have separated html, js and css in the snippet. You should avoid inline js and css.
Good luck!

How to get the text value from divs with same class, and to display in another div?

Example here: http://codepen.io/agentmi6/pen/JoZZWm
how can i display the text of the green div in the grey div, when i click on the [+] icon? Ive tried many different scenarios but none works, can someone give me few pointers how can i do this, i would really appreciate.
<div id="wrapper">
<div class="container">
<div class="first" id="f">
<div class="set">+</div>
this is the 1st element
</div>
<div class="first" id="s">
<div class="set">+</div>
this is the 2nd element
</div>
<div class="first" id="t">
<div class="set">+</div>
this is the 3rd element
</div>
</div>
<div id="cc"></div>
</div>
CSS
.first{
margin-top:5px;
border:1px solid black;
width:190px;
height:40px;
background-color:green;
}
#cc{
margin-top:5px;
width:190px;
height:40px;
border:1px solid black;
background-color:grey;
}
.set{
cursor:pointer;
color:#fff;
font-size:33px;
float:right;
border:1px solid white;
}
You'll have to get the text of the .first div, i suggest you put the text into a tag so it'll be easy to get it, and so you don't get the + of the .get button.
Here's the new JavaScript
$(document).ready(function(){
$('.set').click(function(){
// Get the text inside the span in the parent .first of the clicked .set button
var text = $(this).parent('.first').find('span').text();
$('#cc').text(text);
});
});
The HTML would look like this
<div class="container">
<div class="first" id="f">
<div class="set">+</div>
<span>this is the 1st element</span>
</div>
<div class="first" id="s">
<div class="set">+</div>
<span>this is the 2nd element</span>
</div>
<div class="first" id="t">
<div class="set">+</div>
<span>this is the 3rd element</span>
</div>
</div>
<div id="cc"></div>
Here's an updated CodePen
You can use this:
$(document).ready(function(){
$('.set').click(function(){
var text = $(this).parents("div.first").text();
$("#cc").text(text);
})
});
This Code could help you
var tempText="";
$('.container .set').each(function(){
tempText=tempText+ $(this).html();
});
$('#cc').html(tempText);
Here try this (fiddle: http://jsfiddle.net/nek9fona/)
JQ:
$(function(){
$('.set').click(function(){
var $this = $(this);
var text = $this.parent('.first').text();
$('#cc').text(text);
});
});
Put this in your head html section. Or bottom of body section.
<script>
$(document).ready(function() {
$('.set').on('click', function(){
var text_val = $(this).closest('div.first').text();
$('#cc').text(text_val);
});
});
</script>
I guess that you don't want the copied text to contain "+" symbol? In this case you can do this:
$('.set').click(function() {
var text = $(this.nextSibling).text().trim();
$('#cc').text(text);
});
Demo: http://codepen.io/anon/pen/MYXXrr
Note, that it makes sense to improve HTML structure a little by wrapping the text into some container:
<div class="first" id="s">
<div class="set">+</div>
<div class="text">this is the 2nd element</div>
</div>
In this case, code would become much more reliable and cleaner:
$('.set').click(function() {
var text = $(this).next('.text').text(); // or $(this).parent().find('.text')
$('#cc').text(text);
});
Demo: http://codepen.io/anon/pen/ogyyoO

Categories