Get ID of clicked on element in function - javascript

I want to get the ID of an element I click on.
I put the function in the onclick element, like this:
<a id="myid" class="first active" onclick="markActiveLink();" href="#home">Home</a>
And this is in the function:
function markActiveLink() {
alert($(this).attr("id"));
}
This doesn't work, as it says it isn't defined.
Does it really forget about the ID, do I have to type it in the onclick?

Try: onclick="markActiveLink(this);" and
function markActiveLink(el) {
alert($(el).attr("id"));
}

why using an inline handler? Move to unobtrusive js
$(document).ready(function(){
$('#myid').bind('click', function(){
alert($(this).attr('id'));
});
});

You have to pass the element to the function. JS itself isn't smarter than you :)
html:
<a id="myid" class="first active" onclick="markActiveLink(this);" href="#home">Home</a>
js:
function markActiveLink(e) {
alert(e.id);
}

Do not use $(this) because it does accidentally return the element you added the bind. When you click on an inner element, it also returns the outer element.
<div id="outer">
<div id="inner">
</div>
</div>
You better use the following appearance:
$("#outer").bind('click', function(e) {
if(e.target.id === "inner")
{
alert("you clicked the inner element");
}
else
{
alert("you clicked the outer element");
}
});
You can find a fiddle here: http://jsfiddle.net/vqab7jdo/1/

I try all the ways, spend almost 2 hours and finally found the best way I prefer
try it: < div onclick="div_Clicked(this.id)" id="some"/>
function div_Clicked(itemName) { alert(itemName); }

Related

How to select 'this' onclick?

By triggering an onClick event I would like to select the same element the onClick event is attached to, to add a class to that same element. What I tried is the following:
<div class="class1" onClick="TestFunction();">Click</div>
<script>
function TestFunction() {
$(this).addClass('active');
}
</script>
After clicking the div, the class "active" should be added to the same element, resulting in...
<div class="class1 active" onClick="TestFunction();">Click</div>
However this doesn't work. I am wondering whether the this selector works differently in this case.
The structure of the div element should stay the same and also the function should stay in the same place as it is on the onClick attribute.
The reason is this refers to the global Window object inside the function.
You have to pass this to the function so that you can refer that inside the function:
.active{
color:green;
font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="class1" onClick="TestFunction(this);">Click</div>
<script>
function TestFunction(el) {
console.log(this.constructor.name) //Window
$(el).addClass('active');
}
</script>
Though it is better to avoid inline event handler:
$('.class1').click(function(){
$(this).addClass('active');
});
.active{
color:green;
font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="class1">Click</div>
When using an inline handler the function invoked runs under the scope of the window element, not the element which raised the event. To work around that you can pass this as an argument:
<div class="class1" onClick="TestFunction(this);">Click</div>
function TestFunction(el) {
el.addClass('active');
}
However this is not good practice. Inline event attributes are outdated and now considered bad practice. The better way to achieve this is to attach unobtrusive event handlers. In plain JS it would look like this:
<div class="class1">Click</div>
document.querySelectorAll('.class1').forEach(el => {
el.addEventListener('click', function() {
this.classList.add('active');
});
});
In jQuery it would look like this:
<div class="class1">Click</div>
jQuery($ => {
$('.class1').on('click', function() {
$(this).addClass('active');
});
});

How to bind click event to element hasn't specific child using jquery?

I have several elements on a page like bottom code.
<div>
click
some content
</div>
They can be clicked and jQuery picks that click. However one of the elements has a a link that is clicked should not be picked as a click of the parent element.
$('div:not(#notme)').on('click', function(e) {
// do something
});
Doesn't seem to work for some reason...
Use :has selector to selecting div element has specific child. In :has use :not.
$("div:has(a:not(#notme))").on("click", function(e) {
console.log("clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
click
some content
</div>
<div>
<a href="#" >click2</a>
some content 2
</div>
You may try:
$('div').on('click', function(e) {
if($(e.target).attr("id") !== "notme") {
// do something
}
});
$('#notme').on('click', function(e) {
e.stopPropagation();
});

How to make the js function "onClick" work only on the container div?

I got a problem with the onClick function. I have to set
display: none;
in a css container div when the user clicks on it, but not when he clicks on the divs which are in the container.
<div id="msg_background" onclick="javascript:closemsg();">
<div id="new_msg_cont">
</div>
</div>
So, i don't want that clicking on "new_msg_cont" the function still works.
Here's the js:
function closemsg() {
document.getElementById('cont').style.height='';
document.getElementById('cont').style.overflow='';
document.getElementById('cont').style.position='';
document.getElementById('msg_background').style.display='none';
}
Thanks in advance.
This is called "bubbling" where the inner elements event 'bubbles' up to the parent element.
You can cancel this with event.stopPropagation():
Inline script
<div onclick="event.stopPropagation();" id="new_msg_cont"></div>
jsFiddle
External script
div onclick="javascript:cancel(event);" id="new_msg_cont"></div>
javascript:
function cancel(e)
{
e.stopPropagation();
}
jsFiddle
try something like this
javascript
function closemsg(event) {
if(event.target.id == "msg_background" ){
alert('you cliked me');
document.getElementById('cont').style.height='';
document.getElementById('cont').style.overflow='';
document.getElementById('cont').style.position='';
document.getElementById('msg_background').style.display='none';
}
}
html
<div id="msg_background" onclick="closemsg(event);">
div1
<div id="new_msg_cont">
div2
</div>
</div>
Try this approach:
<div id="msg_background" onclick="javascript:closemsg(this);">
<div id="new_msg_cont">
... your code ...
</div>
</div>
JS CODE
function closemsg(ele) {
if(ele.id === 'msg_background'){
document.getElementById('cont').style.height='';
document.getElementById('cont').style.overflow='';
document.getElementById('cont').style.position='';
document.getElementById('msg_background').style.display='none';
}
}
Inside your function check out if the event was fired by your parent div:
if (ev.target.id == "msg_background")
{
//execute the contents of the closemsg function
}
(ev is the event parameter)
Working Demo: http://jsfiddle.net/kVuKA/1/

jQuery - If DIV class equals X, hide all other DIVs with a different class

I'm new with jQuery and fairly new to JS (a little knowledge) and I'm wanting to create a jQuery code.
Firstly, here is my HTML code:
<div id="user-controls">
<div class="choice" id="choice-all" onclick="showAll();">All</div>
<div class="choice" id="choice-asus" onclick="justASUS();">ASUS</div>
<div class="choice" id="choice-htc" onclick="justHTC();">HTC</div>
</div>
<div id="devices">
<div class="android asus">Nexus 7</div>
<div class="android htc">One S</div>
<div class="android htc">One X+</div>
<div class="android asus">Transformer Prime</div>
<div class="winph htc">Windows Phone 8X</div>
</div>
I'm wanting a jQuery code that would do the following:
If I click on the #choice-asus DIV, then all DIVs with the class .htc would be set to display="none"
If I click on the #choice-htc DIV, then all DIVs with the class .asus would be set to display="none"
If I click on the #choice-all DIV, then all DIVs would be set to display="inline-block" (this is also the default setting when the page first loads)
I've already tried the following code, but it doesn't do anything.
$(document).ready(function(){
$("#choice-htc").click(function(){
$(".htc").hide();
})
});
Thank you for any help,
Dylan.
So many choices :) http://jsfiddle.net/9RtUE/
$(function(){
$("#user-controls").on('click','div',function(){
var classToShow = this.id.split('-')[1],
filter = classToShow === "all" ? 'div': '.' + classToShow;
$("#devices").children().show().not(filter).hide();
});
});
try using jquery
Demo
$('#choice-all').click(function(){
$('.htc, .asus').show();
});
$('#choice-asus').click(function(){
$('.asus').show();
$('.htc').hide();
});
$('#choice-htc').click(function(){
$('.htc').show();
$('.asus').hide();
});
Demo here
$(document).ready(function(){
$(".choice").click(function(){
$(".android,.winph").hide();
if($(this).attr("id")=="choice-all"){
$(".android,.winph").show();
}else if($(this).attr("id")=="choice-asus"){
$(".asus").show();
}else if($(this).attr("id")=="choice-htc"){
$(".htc").show();
}
});
});
to keep it easy and clean you should use a solution such as this one
$(function(){
$('#choice-asus').on('click', function(){
$('#devices > div:not(.asus)').hide();
});
});
it basically says, if you click on #choice-asus, hide all divs in #devices which have no class asus.
you can extend / modify this for your own needs.
besides, its recommend to use jquerys .on() method instead click/bind or what ever handler you'd apply.
$(document).ready(function(){
if($('div').attr('class')=='X')
{
$('div').not($(this)).css('display','none');
}
});
You can try the following code-
function showAll(){
$("#devices div").show();
}
function justASUS(){
$("#devices div").hide();
$("#devices .asus").show();
}
function justHTC(){
$("#devices div").hide();
$("#devices .htc").show();
}
demo here.

How to show/hide a div on mouseover? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to show/hide a div on mouseover using jquery?
I have a div like this:
<div id="parent">
foo
<div id="child" style="display:none;">
hidden
</div>
</div>
I want to have the child div shown whenever someone moves their mouse over the parent div, and when he moves his mouse away, to hide the parent div.
However if I do this:
$("#parent").mouseover(toggle);
$("#parent").mouseout(toggle);
function toggle()
{
console.log('here');
$("#child").toggle();
}
Then both events seem to get called twice each time i move my mouse over the #parent div. How can I achieve what I want?
$("#parent").hover(
function(){
$("#child").show();
},
function(){
$("#child").hide();
}
)
How about add css?
#parent #child{display:none;}
#parent:hover #child{display:block;}
with
<div id="parent">
foo
<div id="child" >
hidden
</div>
</div>
You shouldn't use toggle in this case. If you always want to hide on mouseout and show on mouseover, then define them as such :)
$("#parent").mouseover(function() {
$("#child").fadeIn(); // or .show() for no fading
});
$("#parent").mouseout(function() {
$("#child").fadeOut(); // or .hide() for no fading
});
Don't use toggle function !!
Try something like this:
$("#parent").hover(function(){
$("#child").show();
}, function(){
$("#child").hide();
}
)
This should probably work!!
Shorter:
$("#parent").hover(function () {
$("#child").toggle();
});​
Demo.
Note: You can subtitute toggle with fadeToggle or slideToggle.
You can try .hover() like this,
$('#divid').hover(
function(){
//mouseenter function
},
function(){
//mouseleave function
}
);
You should use something like this:
$("#parent").mouseover(function(){
$('#child').show();
});
$("#parent").mouseout(function(){
$('#child').hide();
});​
jsFiddle example: http://jsfiddle.net/phcwW/
<div id="parent" onmouseover="callMouseOver()" onmouseout="callMouseOut()">
foo
<div id="child" style="display:none;">
hidden
</div>
</div>
Js Method:
function callMouseOver(){
document.getElementById("child").style.display = "inline";
}
function callMouseOut(){
document.getElementById("child").style.display = "none";
}

Categories