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(){});
Related
I have HTML code for kind of blog page. Below - code of 1 post and its height cuts by CSS. It will be many posts on blog page. I want to see all content of particular page by clicking "Read More" button.
Div with blog content has dynamic id which gets from database by PHP.
How can I change height of div with class "blog_article" by clicking "Read More" button?
I thought of using JS/Jquery but cannot get id of "blog_article" div.
Or maybe there is some better way to do this?
<div class="blog_article_wrapper">
<div class="blog_article" id="<?php echo $id; ?>">
<!--Some content-->
</div>
<div class="blog_article_read_more">
<button onclick="blogReadMore()">Read More</button>
</div>
</div>
but cannot get id of "blog_article" div
Why can't you?:
<button onclick="blogReadMore(<?php echo $id; ?>)">Read More</button>
Or, if it's a string:
<button onclick="blogReadMore('<?php echo $id; ?>')">Read More</button>
Then blogReadMore() has a reference to the id:
function blogReadMore(id) {
// use the id to identify the element and modify it however you want
}
Conversely, since you tagged jQuery, you can traverse the DOM from the button click to determine the element without needing any id at all. Something like this:
$('.blog_article_read_more button').click(function () {
var article = $(this).closest('.blog_article_wrapper').find('.blog_article');
// do whatever you like with the article
});
There's a more straight forward way than Azim's answer, but based on the same ideas:
I would still use the read_more class, although not actually needed. I will assume such a class applied to the button.
$('.read_more').click(function(){
var blog_article = $(this).parent().parent().find('.blog_article');
blog_article.css('height', '100px'); //change height here
});
In this case I use .parent() method in order to get the parent object from the clicked item, rather than relying on .closest(). Two calls to .parent() are needed because the <button> resides inside a <div> and we need the parent of that div before we can drill down.
Alternatively:
$('.read_more').click(function(){
var blog_article = $(this).parent().prev();
blog_article.css('height', '100px'); //change height here
});
Because the button's parent <div> is the direct sibling of the one we're interested in. No selectors needed at all!
You have the id right there, you can generate it just fine with blogReadMore('<?php echo $id; ?>'). But you don't need the id, your button lives inside the thing you need expanded so you can look it up that way, too.
You're using fairly ancient JS event handling techniques so this won't be as clean as modern code should be (which doesn't use onclick and other things, but adds the event listening after the DOM has been set up), but you can just pass onclick="blogReadMore(this)" so that your blogReadMore function knows the element that triggered it. Then you just go through the sequence of element.parentNode until you find the element with element.classList.contains('blog_article')===true (both of those have equivalent jQuery calls)
Sort of an answer, but the real one would be "this is not a very good way to generate your code. Generate the HTML and then attach the JS event handling afterwards".
Use a class for read more button, say read_more like <button class="read_more">Read More</button>. And use following jquery.
$('.read_more').click(function(){
var blog_article = $(this).closest('.blog_article_wrapper').find('.blog_article');
blog_article.height(100); //change height here
});
How could I make an element visible in html? for example lets say I have a button in html
<button id="test" hidden="true">
And I would like it to become visible via js once a function is triggerd . How could I do that?
You will need to remove the hidden attribute from the button DOM Object like this:
function showButton(){
var btn = document.getElementById("test");
btn.removeAttribute("hidden");
}
see a running example here:
https://jsfiddle.net/hmg5zdej/
alternatively you can use the more common style rule in stead of the hidden attribute
display: none;
If you are using jQuery, it is even more straight forward:
function showButton(){
$("#test").show();
}
see jQuery documentation:
http://api.jquery.com/show/
http://api.jquery.com/hide/
http://api.jquery.com/toggle/
Think of the following HTML code to apply Jquery:
HTML code:
<div id="outer_div">
<div id="inner_div_1"></div>
<div id="inner_div_2"></div>
<div id="inner_div_3"></div>
</div>
By default, the "outer_div" is hidden. It appears while clicked on a button using Jquery show() function.
I wanted to do the following: On click within anywhere of "outer_div" excluding the area within "inner_div_1" , the "outer_div" would again be hidden. I failed while tried the following codes. What should I amend?
Attempted Jquery 1:
$("#outer_div:not(#inner_div_1)").on("click",function(){
$("#outer_div").hide("slow");
});
Attempted Jquery 2:
$("#outer_div").not("#inner_div_1").on("click",function(){
$("#outer_div").hide("slow");
});
Your support would be highly appreciated.
You need to consider that a click in the inner div is also a click on the outter div. That being said, you just need to check the target and target parents :
$("#outer_div").on("click",function(e){
if(!$(e.target).closest('#inner_div_1').length) $("#outer_div").hide("slow");
});
You can use some of the data in the event
$("#outer_div").on("click",function(e){
if( // Fast check to see if this is the div
e.target.id !=='inner_div_1'
// We limit the 'closest()' code to the outer div. This adds children to the exclude
&& $(this).closest('#inner_div_1, #outer_div')[0].id=='outer_div'){
alert('good click');
}
});
This is a solution for your code now, this works perfect when not too many excluding objects. But no wildcard selectors, which is nice.
And a jsFiddle demo.
Other properties can be used to, like a class:
$("#outer_div").on("click",function(e){
if( e.target.className!=='even'
&& $(this).closest('.even, #outer_div')[0].id=='outer_div'){
alert('yay, clicked an odd');
}
});
I made 7 lines, gave the even ones a class 'even'.
I have the following:
<div class="tab-pane" id="message">
<textarea rows="4" cols="50" id="send_message" placeholder="Enter text ..."> </textarea>
OK
Cancel
I want to bind the click method to the 'div' element , and when one of the child 'a' elements is clicked do separate things. I am trying to distinguish between them using the button text, but the following is not working:
$(function(){
$('#message').click(function(){
if($(this + ">a").is(":contains(OK)")) {
console.log("OK!!");
How can I fix this?
Okay there are two ways of doing this:
.find(selector)
if(this).find("a").is(":contains(OK)")) {
console.log("OK!!");
OR
$(selector,context)
if("a",this).is(":contains(OK)")) {
console.log("OK!!");
In javascript, this is essentially the context of the current function. In jQuery event callbacks, this is set to be the source element of the event - not the selector string, which is what you are treating it as.
Instead, you want to do a test like: if($("a", this).is(":contains(OK)")) {
This works because the second parameter to the jQuery selector is the context to search in, so you are only searching for the a tags under the source element of the click.
Binding the click element to the Div, then checking the text string of the A tags will make both events happen on every click. You want to bind 2 separate click events on each A tag. Add an ID to each A tag, then try this code
$('#okLinkID').click(function(){
console.log("OK!!");
});
$('#cancelLinkID').click(function(){
console.log("Cancel!!");
});
//Attaches only one listener to the #message div and listens for any 'a' element within it to be clicked.
$('a','#message').on('click',function(){
var $this = $(this),
btnText = $this.text();
console.log(btnText);
});
http://jsfiddle.net/YA7Ds/
I have a navigation menu with about 10 items, and I put together this code to update the links for which is selected and which is not. It manually updates classes. The problem is, as you can probably tell, its inefficient and its a pain to update. Is there a better way of doing it?
$('#Button1').click(function(){
$('#Button1').addClass("selectedItem");
$('#Button2').removeClass("selectedItem");
$('#Button3').removeClass("selectedItem");
$('#Button4').removeClass("selectedItem");
$('#Button5').removeClass("selectedItem");
$('#Button6').removeClass("selectedItem");
$('#Button7').removeClass("selectedItem");
$('#Button8').removeClass("selectedItem");
$('#Button9').removeClass("selectedItem");
$('#Button10').removeClass("selectedItem");
});
You could try something like this -
$("[id^='Button']").removeClass("selectedItem");
$('#Button1').addClass("selectedItem");
This will first remove all the selectedItem classes from any element which has an id attribute starting with "button". The second command then adds the class to Button1
You could also simply bind all the elements with the same handler like this -
var $buttons = $("[id^='Button']");
$buttons.on('click', function ()
{
$buttons.removeClass("selectedItem");
$(this).addClass("selectedItem");
});
For each element, when clicked, the class will be removed - the element that was clicked with then have the class added.
Checkout the Attribute Starts With Selector [name^="value"] selector.
I would suggest using classes because this is exactly what they are for - to denote groups of elements. While you can easily select your buttons using the method proposed by Lix (and you should use this method if you can't modify HTML), using class is a more unobtrusive:
var $buttons = $('.button').on('click', function() {
$buttons.removeClass('selectedItem');
$(this).addClass('selectedItem');
});
Meta example: http://jsfiddle.net/88JR2/
You could have a class .button and apply it to all your buttons then
$('#Button1').click(function(){
$('.button').removeClass("selectedItem");
$('#Button1').addClass("selectedItem");
});