Using $(this) when selecting a div - javascript

I have a series of divs all of the same class with no IDs. I want to change the background of the div when it is clicked. I tested the function and it works fine. But when I access the element as this, it is not working. Question is how to get buttonpressed() to work only for the div clicked on?
HTML
<div id="navbar">
<div class="navitem" onclick="buttonpressed()"><p>Membership</p></div>
<div class="navitem" onclick="buttonpressed()"><p>Certification</p></div>
<div class="navitem" onclick="buttonpressed()"><p>Foundation</p></div>
<div class="navitem" onclick="buttonpressed()"><p>Seminars</p></div>
<div class="navitem" onclick="buttonpressed()"><p>Councils</p></div>
</div>
Javascript
function buttonpressed() {
var bgString = "url('navbuttonpressed.png')";
$(this).css('backgroundImage',bgString);
}

Since you're using jQuery you can (and should) remove the inline event handling and just use:
$( document ).ready(function() {
$('.navitem').click(function(){
var bgString = "url('navbuttonpressed.png')";
$(this).css('backgroundImage',bgString);
})
});
jsFiddle example

When using HTML inline event handlers, this references your window. If you instead attach an event handler through JavaScript, it will work as expected:
$(".navitem").on("click", function () {
var bgString = "url('navbuttonpressed.png')";
$(this).css('backgroundImage',bgString);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="navbar">
<div class="navitem"><p>Membership</p></div>
<div class="navitem"><p>Certification</p></div>
<div class="navitem"><p>Foundation</p></div>
<div class="navitem"><p>Seminars</p></div>
<div class="navitem"><p>Councils</p></div>
</div>

You could get access to this if you change how you're catching the event:
$('.navitem').on('click', function() {
var bgString = "url('navbuttonpressed.png')";
$(this).css('backgroundImage',bgString);
})
HTML
<div id="navbar">
<div class="navitem" ><p>Membership</p></div>
<div class="navitem" ><p>Certification</p></div>
<div class="navitem" ><p>Foundation</p></div>
<div class="navitem"><p>Seminars</p></div>
<div class="navitem" ><p>Councils</p></div>
</div>

As mentioned in the comments, one way to do this would be:
$('.navitem').click(function(){
var bgString = "url('navbuttonpressed.png')";
$(this).css('backgroundImage',bgString);
});
Check: https://api.jquery.com/click/
Also keep in mind, that the code above will bind this function to all elements with the css-class "navitem". In case you do not know, what this means you might check as well: https://api.jquery.com/category/selectors/

$(".navitem").click(function(){
$(this).css('background-image', 'url(https://www.google.pt/images/nav_logo195.png)');
});
Demo:
http://codepen.io/tuga/pen/bdddGa

If you happened to want a pure JS solution and if you want to keep your inline onClick listeners, you could do this..
HTML
<div class="navitem" onclick="buttonpressed(this)"><p>Membership</p></div>
JS
function buttonpressed(element) {
var bgString = "url('navbuttonpressed.png')";
element.style.backgroundImage = bgString;
}
The this keyword passes the element that called the function through to the method itself.
This works well - JSFiddle

Related

toggle div using for loops

just wondering what went wrong.. i have two div named click_1 and click_2.. and i want to toggle the div named hide corresponding with their numbers.. lets say click_1 with hide_1 and click_2 with hide_2.. but when i ran the code only click_1 is functioning .. what seems to be wrong... newbie here.. recently learned jquery
<div id='click_1'>
<div id='hide_1'></div>
</div>
<div id='click_2'>
<div id='hide_2'></div>
</div>
<script>
function toggle_div(id_A,id_B){
for(var i=0; i<3; i++){
var new_A = id_A + i;
var new_B = id_B + i;
$(new_A).click(function(){
$(new_B).toggle();
});
}
}
toggle_div('click_','hide_');
</script>
The issue is because your id selectors are missing the # prefix:
toggle_div('#click_', '#hide_');
However you should note that you will also need to use a closure for this pattern to work otherwise the new_B element will always be the last one referenced in the for loop.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='click_1'>
click 1
<div id='hide_1'>hide 1</div>
</div>
<div id='click_2'>
click 2
<div id='hide_2'>hide 2</div>
</div>
<script>
function toggle_div(id_A, id_B) {
for (var i = 1; i < 3; i++) {
var new_A = id_A + i;
var new_B = id_B + i;
(function(a, b) {
$(a).click(function() {
$(b).toggle();
})
})(new_A, new_B);
}
}
toggle_div('#click_', '#hide_');
</script>
As you can see this is very verbose, rather complicated and hardly extensible. A much better approach is to use generic classes and DOM traversal to repeat the same logic on common HTML structures.
To achieve this put common classes on the elements to be clicked and the elements to toggle. Then in the single click event handler you can use the this keyword to reference the element which was clicked, then find() the element to toggle within that. Something like this:
$(function() {
$('.click').click(function() {
$(this).find('.hide').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="click">
click 1
<div class="hide">hide 1</div>
</div>
<div class="click">
click 2
<div class="hide">hide 2</div>
</div>
<div class="click">
click 3
<div class="hide">hide 3</div>
</div>
Also note that this pattern means that you can have an infinite number of .click elements with matching .hide content without ever needing to update your JS code.
It is better not to use for loop for click event ! If you have id like that your can handle by that clicked id split ....
$("[id^='click_']").on("click",function () {
$('#hide_'+this.id.split('_')[1]).toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='click_1'>
Click1
<div id='hide_1'>hide1</div>
</div>
<div id='click_2'>
Click2
<div id='hide_2'>hide2</div>
</div>

Javascript - populate a div with content from a hidden div using click buttons

I need some help. As you will see in my fiddle, I am attempting to use buttons to populate a single container div with content from multiple hidden divs, depending on which button is clicked. The problem I am having is, I don't know how to access the actual content in the hidden divs to populate the container div. As of now, I am using the id attributes for the hidden divs to demonstrate which div content I would like to display in the container.
I've seen a few other posts with link <a> attributes referencing hidden content, but none so far using a button element with click functionality to change div content.
jQuery(function ($) {
$('#button1').click(function () {
$('#info').empty();
$('#info').prepend('#option1');
});
$('#button2').click(function () {
$('#info').empty();
$('#info').prepend('#option2');
});
$('#button3').click(function () {
$('#info').empty();
$('#info').prepend('#option3');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button-panel">
<ul id="button-column" style="list-style: none;">
<li class="buttons"><button id="button1">Button 1</button></li>
<li class="buttons"><button id="button2">Button 2</button></li>
<li class="buttons"><button id="button3">Button 3</button></li>
</ul>
</div>
<div id="info-div">
<div id="info"></div>
</div>
<div id="hiddenDivs" style="display:none;">
<div class="info" id="option1">Box</div>
<div class="info" id="option2">Google Drive</div>
<div class="info" id="option3">Box</div>
</div>
Here is my fiddle
Here's a version that uses jquery data attributes. It reduces the redundancy and complexity and can be configured easily.
<body>
<div class="button-panel">
<ul id="button-column" style="list-style: none;">
<li class="buttons"><button id="button1" data-link="option1">Button 1</button></li>
<li class="buttons"><button id="button2" data-link="option2">Button 2</button></li>
<li class="buttons"><button id="button3" data-link="option3">Button 3</button></li>
</ul>
</div>
<div id="info-div">
<div id="info">
</div>
</div>
<div id="hiddenDivs" style="display:none;">
<div class="info" id="option1">Box</div>
<div class="info" id="option2">Google Drive</div>
<div class="info" id="option3">Box</div>
</div>
</body>
<script>
$('.buttons button').click(function (){
$('#info').empty();
$('#info').html($("#" + $(this).data('link')).html());
});
</script>
Example : https://jsfiddle.net/yvsu6qfw/3/
It sounds like maybe you were looking for using the button itself to populate data built into the button with a data attribute or something? If so you can do something like this:
HTML
<div class="button-panel">
<ul id="button-column" style="list-style: none;">
<li class="buttons"><button data-info="Box">Button 1</button></li>
<li class="buttons"><button data-info="Google Drive">Button 2</button></li>
<li class="buttons"><button data-info="Box">Button 3</button></li>
</ul>
</div>
<div id="info-div">
<div id="info"></div>
</div>
jQuery
$(document).ready(function (){
$('#button-column button').click(function (){
$('#info').html($(this).attr('data-info'));
});
});
If you want the first button to load the content from the first hidden div etc. without relying upon using the id attributes, you can use the .index() method. When you pass this as an argument it will return the index value of the click event target in the collection $("#button-column .buttons :button"). Afterwards you can pass the index value to the .get() method to retrieve the corresponding element from the collection of hidden divs $("#hiddenDivs .info").
$().ready(function(){
$("#button-column .buttons :button").on("click", function(){
$('#info').empty();
var clickedIndex = $("#button-column .buttons :button").index(this);
var hiddenInfo = $("#hiddenDivs .info").get(clickedIndex);
$('#info').prepend( $(hiddenInfo).text() );
});
});
you can use html function, without parameter gets the content of the element
with parameter replaces the content with the string parameter
$(document).ready(function (){
$('#button1').click(function (){
$('#info').html( $('#option1').html() );
});
$('#button2').click(function (){
$('#info').html( $('#option2').html() );
});
$('#button3').click(function (){
$('#info').html( $('#option3').html() );
});
});
In your code example, you do for example:
$('#info').prepend('#option1');
What you instruct to do here, is adding a text string '#option1' to an element with ID info.
What you intend to do is prepending the content of ID option1 to the element with ID info. You could do something like this instead:
$('#info').prepend($('#option1').html());
Another approach could be (but I don't know if that's relevant for you) to not clone content (since it costs you repaints) but toggle the specific elements instead. For example:
$('#option1,#option2').hide();
$('#option3').hide();
And yet another one: use data-attributes on your buttons:
Button 1
Button 2
<div id="info">
</div>
And the JS:
$('.button').on('click', function(event) {
event.preventDefault();
$('#info').html($(event.currentTarget).attr('data-text'));
});
Don't repeat yourself! To get the number out of an ID replace with "" all that is not a number using RegExp \D.
Using number from ID
Than, to get the actual content you can use $("#option"+ num).html() or $("#option"+ num).text() methods:
jsFiddle demo
jQuery(function ($) {
$('.buttons button').click(function () {
var num = this.id.replace(/\D/g,"");
$("#info").html( $("#option"+ num).html() );
});
});
Target element using data-* attribute
Alternatively you can store inside a data-* attribute the desired target selector ID:
<button data-content="#option1" id="button1">Button 1</button>
and than simply:
jsFiddle demo
jQuery(function ($) {
$("[data-content]").click(function () {
$("#info").html( $(this.dataset.content).html() );
});
});
http://api.jquery.com/html/
http://api.jquery.com/text/
If the expectation is to get same indexed hidden div content, Then the below code should work.
$(document).ready(function (){
$('.buttons button').click(function (){
$('#info').empty();
var index = $('.buttons button').index($(this));
$('#info').html($('.info:eq('+index+')').html());
});
});

Jquery get closest a href attribute

I have the below markup and I am trying to get the href but always getting undefined. Any help is appreciated.
<div class="wrapper">
<span class="mixSpanLeft" style="background-image: url(http://cdn.wallpapersafari.com/29/20/3HE5Mx.jpg)">
</span>
<div class="mixDivRight">
<p class="bottomP"><button>Select</button><p>
</div>
</div>
$container = $('.wrapper');
$container.on('click', '.bottomP', function (event) {
console.log($(this).closest('a').attr('href'));
});
Assuming that you fix the class/ID issue noted in the comments by Mohammad you could use:
$('.wrapper').on('click', '.bottomP', function (event) {
console.log($(this).closest('.wrapper').find('a').attr('href'));
});
$('.wrapper').on('click', '.bottomP', function (event) {
console.log($(this).closest('.wrapper').find('a').attr('href'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<span class="mixSpanLeft" style="background-image: url(http://cdn.wallpapersafari.com/29/20/3HE5Mx.jpg)">
</span>
<div class="mixDivRight">
<p class="bottomP"><button>Select</button><p>
</div>
</div>
Aside from what Mohammad mentioned about needing to use .wrapper instead of #wrapper. I recommend using .find() instead of .closest(). .closest() does not work in IE, but that might not be an issue for you. you can also do something like this:
$("div.wrapper").on('click', '.bottomP', function () {
console.log($("div.wrapper a:first").attr('href'));
});
This will grab the first <a> tag inside the wrapper div.

Multiple Click function on Javascript

I am new to javascript and i m using this script :
<script type="text/javascript">
$(document).ready
(function()
{
$('#apply').click(function()
{
$('#applyinfo').toggle("slow");
});
});
</script>
for the on click function when i click on apply it as to display the apply info div. this function is working however if i create multiple apply id it is not working. Please help me on this.
If you wish to bind the click function for multiple dom elements you can use it as,
$(document).ready(function() {
$('#apply,#apply1,#apply2').click(function() {
$('#applyinfo').toggle("slow");
});
});
with , delimiter. However you cant name the same id's for various html elements. In that case go for a class selector as #Pranav suggested in comments
For ex,
$('.applyClass').click(function() { .. } );
id should be unique , so use common class to all those items
<script type="text/javascript">
$(document).ready(function() {
$('.apply').click(function() {
//-^-- class selector
$('#applyinfo').toggle("slow");
});
});
</script>
Try this solution:
$(document).ready(function() {
$("[id$='apply']").click(function() {
$('#applyinfo').toggle("slow");
});
});
An id should be unique, so having multiple #apply and #applyinfo isn't a option. Instead, switch to classes.
The function depends on your HTML though.
If .applyinfo is a child of .apply this works:
HTML:
<div class="apply">Click here
<div class="applyinfo">Toggle this info</div>
</div>
jQuery:
$(function() {
$('.apply').click(function() {
$(this).find('.applyinfo').toggle("slow");
});
});
DEMO
$(function() {
$('.apply').click(function() {
$(this).find('.applyinfo').toggle("slow");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="apply">Click here
<div class="applyinfo">Toggle this info</div>
</div>
<div class="apply">Click here
<div class="applyinfo">Toggle this info</div>
</div>
<div class="apply">Click here
<div class="applyinfo">Toggle this info</div>
</div>
If the .applyinfo is not a child of .apply we need to find the matching div. The function then becomes:
HTML:
<a class="apply-1">Click</a>
<a class="apply-2">Click</a>
<a class="apply-3">Click</a>
<div class="applyinfo-1">Belongs to a.apply-1</div>
<div class="applyinfo-2">Belongs to a.apply-2</div>
<div class="applyinfo-3">Belongs to a.apply-3</div>
jQuery:
$(function() {
$('[class^=apply-]').click(function() {
var nr = $(this).attr('class').split("-").pop() ,
selector = '.applyinfo-'+nr;
$(selector).toggle("slow");
});
});
DEMO
$(function() {
$('[class^=apply-]').click(function() {
var nr = $(this).attr('class').split("-").pop() ,
selector = '.applyinfo-'+nr;
$(selector).toggle("slow");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="apply-1">Click</a>
<a class="apply-2">Click</a>
<a class="apply-3">Click</a>
<div class="applyinfo-1">Belongs to a.apply-1</div>
<div class="applyinfo-2">Belongs to a.apply-2</div>
<div class="applyinfo-3">Belongs to a.apply-3</div>

Select contents of div to fadeIn sequentially

I'm not sure the best way to word this, so hopefully this makes sense.
Currently, on my page, all my elements fadeIn on click. What I would like is for a few select elements in an id (#seqFade below) to fade in on their own when that parent fadeIn class is clicked.
I've figured out how to make both of these effects work on separate pages, but I can't figure out how to have them both occur on the same page / combine the two.
Here is more or less how my page is designed, and below is what I have so far for code.
HTML
<div id="content">
<div class="fadeIn">
<p>Hello</p>
</div>
<div class="fadeIn" id="seqFade">
<span>1</span>
<span>2</span>
<span>3</span>
</div>
<div class="fadeIn">
Bye.
</div>
</div>
SCRIPT
$(document).ready(function(){
//hides all fadeIns
$('.fadeIn').hide();
$(document).on('click',function() {
if('#seqFade') {
//sequential fadeIn function (works)
$('span').each(function(i) {
$(this).delay(i*300).fadeIn('slow');
});
}
//fadeIn on click (works)
$('.fadeIn:hidden:first').fadeIn('slow');
})
.click();
Thank you so much in advance.
JSfiddle of full page //
JSFiddle of both effects working
Try this, just add a class on hidden at the beginning for the spans
$(document).ready(function() {
var timeOuts = new Array();
var eT=200;
function myFadeIn(jqObj) {
jqObj.fadeIn('slow');
}
function clearAllTimeouts() {
for (key in timeOuts) {
clearTimeout(timeOuts[key]);
}
}
$(document).on('click',function() {
$('#seqFade span').hide().each(function(index) {
timeOuts[index] = setTimeout(myFadeIn, index*eT, $(this));
});
});
});
http://jsfiddle.net/h67vk02w/2/
HTML
<div id="content">
<div class="fadeIn">
<p>Hello</p>
</div>
<div class="fadeIn" id="seqFade">
<span>L</span>
<span>o</span>
<span>a</span>
<span>d</span>
<span>i</span>
<span>n</span>
<span>g</span>
<span>.</span>
<span>.</span>
<span>.</span>
</div>
<div class="fadeIn" id="bye">
Bye.
</div>
Javascript
$(function() {
$('.fadeIn').find('span').toggle();
$('#hello, #bye').toggle();
$(document).click(function() {
$('#hello').fadeIn('slow');
$('span').each(function(i) {
$(this).delay(i*300).fadeIn('slow', function() {
$(document).unbind('click')
.bind('click', () => $('#bye').delay(300).fadeIn('slow'));
});
});
});
});
JSFiddle: http://jsfiddle.net/6mLgu3om/3/
Or like that?
Use the classes for this (add some fade/noFade classes to elements). ID must be unique. And after that just check if the element has that class like this. Now you have basically unlimited options to do this. Just add more classes / check and do something.
$(".class_of_element").hasClass("your_class")

Categories