I have JS below that i am trying to dispaly a menu item once the image is clicked under the image and once an item is clicked it disappears. i have multiple images that is why i am building this dynamic content menu. i am planning to add bunch of html element inside userMenuContent by
using var userMenuContent ="<div><form>...</<form></div>";
but to begin with my small test fails
function userMenu() {
var userMenudiv = document.createElement("div");
userMenudiv.setAttribute("class", "statusContainer");
var userMenuContent = "<p>test</p>";
$(userMenudiv).append($(userMenuContent));
$(userMenudiv).hide();
this.appendChild(userMenudiv);
$(userMenudiv).slideDown();
}
<img class="icon" src="image.png" onclick="userMenu()"/>
when i click the image i get
TypeError: this.appendChild is not a function.
i am using jquery 1.8.3 and jquery-ui1.8.24
'this' refers to the window object, not the image.
Don't use inline event handlers. Give the DOM element an id and select it that way.
You can't add a div to an image. Instead, you need to specify another target element
Since you're using jQuery, just do it the jQuery way.
$(document).ready(function(){
$('#userMenuImg').click(function(){
$('#target')
.append('<div class="statusContainer"><p>test</p></div>')
.slideDown();
});
});
<img id="userMenuImg" class="icon" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRMKbTxKTOJbJvVTt2SZak49lARNnCU4D7ECfZn1KspIn6SXDHz3A">
<div id="target"></div>
Related
How do you use $(this) with a JS function and then find the attr?
function date_box() {
alert(this.getAttribute(week));
}
I want to get the attribute week from an element called gospel_table4. On click of gospel_table4, the function is triggered:
<a href='#'><div id='gospel_table4' week='$one_date' onclick='date_box()'> Week $one_date </div></a>
I can't do this:
$(this).click...
Because only one element of gospel_table4 is clickable. With the other method, all the elements of gospel_table4 are clickable.
Basicially, how do I get the attr from the function of date_box()?
You need a param inside your function
HTML:
<a href='#'><div id='gospel_table4' week='$one_date' onclick='date_box(this)'> Week $one_date </div></a>
Javascript:
function date_box(thisdiv){
alert($(thisdiv).attr("week"));
}
JAVASCRIPT
function date_box(that)
{
$attr=that.getAttribute('week');
alert($attr);
}
<a href='#'><div id='gospel_table4' week='$one_date' onclick='date_box(this)'> Week $one_date </div></a>
so the reason why click is not working is that div is inside anchor tag,
and anchor is clicked there are references like Anchor tag becomes non-working link in a div with float: right; or Is putting a div inside an anchor ever correct? which can give more details. So following is the code in jQuery()
$("#gospel_table4").parent("a").click(function(){
var week = $(this).children("#gospel_table4").attr("week");
console.log(week);
});
Explanation : Since we know that anchor is clicked first we place the click event listener on anchor tag . Then we can access the relative child element.
This will work but date_box() will also be invoked at the same time, I would recommend that you remove the onclick and and place it in side the above that way you would have more control over the code. Hope this is helpful.
I have added Elements using Jquery inside PHP after loading them from the database. Each button has two classes, one controlling the GUI and another controlling the Click for particular button. The code is as under
echo "<script type='text/javascript'>$('.main').append('<button class=b_ui b$index>Change</button>'); </script>";
Now if I check the classes from Inspect Element perspective of the browser, it shows 2 classes. But when I click on it and get class of element using this code
$('.b_ui').click(function()
{
cls = $(this).attr('class');
alert('no. '+cls);
}
It shows only first class (GUI) and not the other which I want to use for handling click.
Any help ?
Put quotes around the class attribute. <button class=\"b_ui b$index\">Change</button>
You should use "on" method:
$(document).on('click', '.b_ui', function() {
cls = $(this).attr('class');
alert('no. '+cls);
});
When adding elements dynamically to the DOM, they are not accessible by jQuery like an element which was there at page load. say you have this div:
<div id="div"></div>
and you add some content with jQuery so it now looks like this:
<div id="div"><span id="span"></span></div>
you cannot refer directly to the span using jQuery with $('span[id=span]'), you have to target a containing element then filter which contained element you want:
$('#id').on('click','span',function(){});
How do i even put these, let me try. In the following sets of codes, i want to click 'parentclass' and have an alert value of 'child1' and when i click the class below it which is 'Parent 2' have an alert fire with a value of 'child2'
So this must alert the content of that class only and not the entire class.
Here's some Javascript in Jquery.
var childclass = $('.childclass').html();
$('.parentclass').click(function(e) {
alert (childclass)
});
$('.childclass').click(function(e) {
e.stopPropagation()
e.preventDefault()
});
And HTML
<a href="" onClick="return false">
<div class='parentclass'>
Parent 1
<div style="display:none" class="childclass">child1</div>
</div>
</a>
<a href="" onClick="return false">
<div class='parentclass'>
Parent 2
<div style="display:none" class="childclass">child2</div>
</div>
</a>
This line var childclass = $('.childclass').html(); doesnt make sense as it doesn't know which element in particular you mean. The result of that will just be child1child2 which is just a concatenation of the .html() of all the elements with class childclass. This is obviously not what you want.
Therefore you should dynamically find the child with a class of childclass upon receiving the click event.
$('.parentclass').click(function(e) {
alert($(this).find('.childclass').html())
});
Also, you should know that your child class event handler is useless as we don't care if the event gets propogated downwards. If you DID care, then your e.stopPropagation() and e.preventDefault() should be in the event handler of the parent class.
You need to fetch the html of the clicked parent element within the click handler
$('.parentclass').click(function (e) {
alert($(this).find('.childclass').html())
});
$('.childclass').click(function (e) {
e.stopPropagation()
e.preventDefault()
});
Demo: Fiddle
Several ways you can go about this.
First, if your HTML will not be dynamic (elements already exist when page loads), then you can select elements by the parent class name and assign click event as so:
$('.parentclass').click(function(e) {
// the first variable here is selecting the inner elements having class 'childclass'
// keep in mind, if more than one child having that class is present within this parent, it will select all of them
var child = $(this).find('.childclass');
// here we alert the text of the inner child found
// if it is more than one, you will have undesired results. you may want to specify `.first()`
alert(child.text())
})
For newer jQuery you can also use $('.parentclass').on('click', function(e) {.
If you expect any pieces of parentclass to be dynamic, then you'll want to delegate the event based on either a static parent to the parents or document. This can be like so:
$(document).on('click', '.parentclass', function(e) {
alert($(this).find('.childclass').text())
})
Or, if you have a static (already there when page loads) wrapping element, give it an ID like `parentClassWrapper' and assign the click event dynamically as:
$('#parentClassWrapper').on('click', '.parentclass', function(e) {
alert($(this).find('.childclass').text())
})
Some helpful links:
jQuery API
jQuery Selectors
.click()
.on()
Some info on Event Delegation
jquery on vs click methods
jQuery .on('click') vs. .click() and .delegate('click')
jquery .live('click') vs .click()
I made several adjustments to your html that are worth noting. There's no need for the <a> tag. Don't use inline js - onlick in your html. Note that I wrapped the text inside of the div in the <a> tag instead. This markup is more semantic. Also, move your styles to css rather than in the html.
<div class="parent">
<a>Parent 1</a>
<a class="child">child of parent 1 contents</a>
</div>
<div class="parent">
<a>Parent 2</a>
<a class="child">child of parent 2 contents</a>
</div>
css:
.parent > .child { /* good practice: only select an immediate child of the parent */
display: none;
}
The other answers here are using find() to select the child, but I recommend children() instead. For example, if you had additional nested .childs, find() will select them all, but children() will only select direct .childs of the parent, so it is better in this case. I also recommend using the console for debugging rather than alert.
Live demo here (click).
$('.parent').click(function() {
var $child = $(this).children('.child');
var cls = $child.attr('class');
console.log(cls);
$child.show(); //added so that you can click the child
});
$('.child').click(function() {
var html = $(this).html();
console.log(html);
//if you just want the text, use this instead:
var text = $(this).text();
console.log(text);
});
I am trying to create a click event for an image using jQuery but I fail every time I try.
First I have a div:
<div id="price-holder"></div>
then I am using jQuery to insert this HTML by using the following:
$("#price-menu li:nth-child(2)").click(function() {
var pregHTML = $("#cakesmash-price").html();
$("#price-holder").html(pregHTML);
});
However, using this HTML doesn't work
<div id="cakesmash-price" style="display:none">
<img id="cake" src="images/order.png" height="32px" onclick="pregbasic(this);">
</div>
I tried to use the attribute onclick for the image and also tried using jQuery's selector with the ID like so
$("#cake").click(function(){
})
but both didn't work.
Can anyone help me?
Thanks
This assumes that the element is actually being added to the page.
I am betting you are adding the click event before you add the element to the page meaning the selector did not find anything so it did not add the event.
Either add the event after you add the element or use event delegation.
$("#price-holder").html(pregHTML);
$("#cake").click(function(){
});
or
$("#price-holder").on("click", "#cake", function () {
});
Your error could be due to your choice of selectors "#price-menu li:nth-child(2)". Try using the JS .children and .eq selectors. Also if your code was added dynamically consider using the .on() event handler rather than the .click().
Just start with the DOM you actually want, without using jQuery to do this:
<div id="price-holder">
<div id="cakesmash-price" style="display:none">
<img id="cake" src="images/order.png" height="32px">
</div>
</div>
Then you can just add you click handler on #cake:
$('#cake').on('click', function (event) {
// your logic goes here
});
I have the following html, dynamically created.
<a class="open"></a>
<div class="dialog"></div>
<a class="open"></a>
<div class="dialog"></div>
<a class="open"></a>
<div class="dialog"></div>
<a class="open"></a>
<div class="dialog"></div>
Using the follwing jquery, I'm assigning ID's to each a aswell as each div
$('a.open').prop('id', function(i){
return '' + (i + 1);
});
$('div.dialog').prop('id', function(i){
return 'dialog' + (i + 1);
});
I'm then using the assigned ID's to trigger a jquery ui Dialog pop-up, however, I'm having to rewrite the function below for x number of times. Is there a way to create the below function so I do not have to rewrite it x number of times. (x being the max. number of times the the divs may appear on page).
$("#1").click(function(){
$("#dialog1").dialog("open");
});
Sounds like an ideal use for data attributes. When you dynamically generate the <a> tags, assign them a data attribute like so:
<a class="open" data-openNumber="1"></a>
(You can also do this via jQuery, of course).
Then all you have to do is write a single click handler:
$('body').on( 'click', '.open', function(){
var num = $(this).data('openNumber');
$('#dialog'+num).dialog( 'open' );
});
Note that I don't attach the handler directly to elements with class open; if I did that, I would have to do it every time the elements were dynamically created. Instead, I attach the handler to the body, and filter it by class open; that way I don't have to keep re-declaring that click handler. If you have a more handy enclosing class, you can use that instead of body, but not knowing your page structure, I didn't know what that element would be, so I just used body.
I made a jsFiddle to demonstrate the concept. I hope it's helpful:
http://jsfiddle.net/Jammerwoch/Z9U67/
What about this?
HTML
<a class"open" data-id="1">open</a>
<div class="dialog" data-id="1"></div>
JS
$(document).on("click", ".open", function(e) {
var id = $(this).data("id");
$(".dialog[data-id="+ id +"]").dialog("open");
});
If you are only using the id attribute to listen for clicks later on. It makes more sense to create a single event listener for the group.
$("a.open").on("click", function(){
$(this).find(".dialog").dialog("open")
});