Here is my HTML code:
<th>
Click<br/>
<img class="magnifier" height="66" src="../Images/magnifier-zoom.png" width="75"><br/>
To Enlarge
</th>
I have a jQuery script that when clicked it toggles an enlarge class, so when someone clicks to enlarge I want to change the enlarge word to shrink would there be any simple way of doing this in jQuery?
Or do you guys think I am better off having 2 <div>'s or even <span> elements and toggle the display of each element?
There are numerous ways to do this. You could leverage pseudo-element content, do string manipulation with JavaScript, and more. In the end, the best approach is to probably just toggle the visibility of a couple nested elements:
I've placed a default "shrink" class on my td element. Within, I have a couple span elements customized with explicit data-do attributes indicating the purpose of each:
<td class="shrink">
Click to
<span data-do="enlarge">Enlarge</span>
<span data-do="shrink">Shrink</span>
<img src="..." />
</td>
We target the data-do attributes that are nested within elements that have corresponding classes, and we disable the display of these elements:
.shrink [data-do='shrink'],
.enlarge [data-do='enlarge'] {
display: none;
}
In order to toggle the class of the td element, we bind up some simple jQuery:
$("td").on("click", function () {
$(this).toggleClass("shrink enlarge");
});
Anytime a td is clicked (you can make the selector specific to a single td), we add toggle the "shrink" and "enlarge" classes. If "enlarge" was present to begin with, it is removed; otherwise it will be added. The same goes for "shrink".
Change your HTML to
<th>
<div>Click</div>
<img class="magnifier" height="66" src="../Images/magnifier-zoom.png" width="75">
<div>To Enlarge</div>
</th>
To have elements instead of text nodes.
Then you can do simple:
$('.magnifier').click(function() {
var $next = $(this).next();
$next.text($next.text() == 'To Enlarge' ? 'To Shrink' : 'To Enlarge');
})
Demo: http://jsfiddle.net/B7GDQ/
This is the direct answer to your questions, although not the best method:
$(".magnifier").on("click", function () {
if ($(this).hasClass('enlarge')) {
$(this).removeClass('enlarge');
this.parentNode.lastChild.textContent = 'To Enlarge'
}else{
$(this).addClass('enlarge');
this.parentNode.lastChild.textContent = 'To Shrink';
}
});
The ideal method would be to use pseudo elements:
Codepen
HTML:
<div class="magnifier">
Click<br/>
<img height="66" src="../Images/magnifier-zoom.png" width="75"><br/>
</div>
CSS:
.magnifier::after {
content: 'To Enlarge';
}
.magnifier.enlarge::after {
content: 'To Shrink';
}
JS:
$(".magnifier").on("click", function () {
$(this).toggleClass('enlarge');
});
Related
I am trying to verify if the clicked cell on a devexpress grid is valid according to the following rules:
Click on a cell that has classes: .dxgv.dx-ar (This part is working)
If that element contains some element of the class gridValue AND this (child) element has a father with name: 'allowsEdit' (THIS CODE IS NOT WORKIING)
I was trying to avoid using the ".parent()..." adicional line, but combine multiple JQuery selector rules, but till now I was not able.
Any ideas?
JS
$('#' + gridIdName).unbind('click').on('click', '.dxgv.dx-ar', function (e) {
if ($(this).find('.gridValue:parent[name="allowsEdit"]').length !== 0) {
console.log('FOUND');
return
}
console.log('NOT FOUND');
});
HTML
/******** VALID *************/
<td id="devGrid1_tccell2_13" class="dxgv dx-ar">
<div style="width: 100%;" name="allowsEdit" class="contextMenuElement TargetIdstate VarietyId76 Year2018 CountryId2 PlanId11437">
<div style="width:100%;" id="state_76_2_2018" class="gridValue gridValueMin1 gridValueMax11">
2000
</div>
<div style="clear: both;"></div>
</div>
</td>
/******** NOT VALID *************/
<td id="devGrid1_tccell3_7" class="dxgv dx-ar" style="background-color:#E4AA8A;">
<div style="width: 100%;" name="" class="contextMenuElement TargetIdactual VarietyId82 Year2018 CountryId1 PlanId12732">
<div style="width:37px;" id="actual_82_1_2018" class="gridValue">
40000
</div>
<div style="clear: both;"></div>
</div>
</td>
You can use a simple css selector for this
[name="allowsEdit"] > .gridValue
this selects the .gridValue element. if you directly want the allowsEditElement you can use:
[name="allowsEdit"]:has(.gridValue)
find .gridValue class elements where direct parent have class: .allowEdit
$(this).find('[name="allowsEdit"]:has(.gridValue)').length
For more information you can read Mozzila's documentation about this
Click on a cell that has classes: .dxgv.dx-ar
If that element contains some element of the class gridValue AND this element has a father with name: 'allowsEdit'
Your HTML doesn't match that description, but the above is a straightforward combination of:
An attribute value selector
A descendant combinator
A pair of class selectors
A :has selector (which is a jQuery addition)
So all in one it would be: [name=allowsEdit] .dxgv.dx-ar:has(.gridValue)
E.g.:
$('#' + gridIdName).unbind('click').on('click', '[name=allowsEdit] .dxgv.dx-ar:has(.gridValue)', function (e) {
That's if you don't want the clicks at all unless it's a match.
But if you want the click regardless and then just want to check the other things afterward:
$('#' + gridIdName).unbind('click').on('click', '.dxgv.dx-ar', function (e) {
var $this = $(this);
if ($this.closest("[name=allowEdit]").length && $this.find(".gridValue").length) {
// Match
} else {
// No match
}
I submitted my code on a code review site and it highlighted that have duplicate functions within my script which can be seen below.
$(document).ready(function () {
$('#search-btn').click(function () {
$('.search-bar-wrap').toggleClass('searchActive');
$('.more-menu').removeClass('moreMenuActive');
$('account-menu').removeClass('acMenuActive');
});
$('.more-btn').click(function () {
$('.more-menu').toggleClass('moreMenuActive');
$('.account-menu').removeClass('acMenuActive');
$('.nav-bar-wrap').removeClass('searchActive');
});
$('.ac-btn').click(function () {
$('.account-menu').toggleClass('acMenuActive');
$('.nav-bar-wrap').removeClass('searchActive');
$('.more-menu').removeClass('moreMenuActive');
});
// MOBILE
$('#mobile-menu').click(function () {
$('.mobile-menu').toggleClass('mobileMenuActive');
$('.m-accord-dwn').removeClass('accordionActive');
});
$('.active-mobile-menu').click(function () {
$('.mobile-menu').toggleClass('mobileMenuActive');
$('.m-accord-dwn').removeClass('accordionActive');
});
$('.mobile-accordion').click(function () {
$('.m-accord-dwn').toggleClass('accordionActive');
});
});
The click functions demonstrated above are adding and removing classes to show can hidden element on the web page and to also give the click but an active state etc. I am trying to follow best practices for me code. Based on my code above is there a way create a global active function? Jsfiddle
The way to eliminate redundant code is to use classes and structure in your markup. By structuring the markup, the same class should be able to be applied to multiple elements, not just one element like you currently have.
You only need one style in your CSS:
.inactive {
visibility: hidden;
}
Then change your markup so each element to be hidden/shown has a "container" element around it and its button. The buttons that toggle the visibility should all have the "toggle-btn" class. And the elements to be hidden/shown all have the "pane" and "inactive" classes.
<header ...>
<div class="container">
<a class="toggle-btn ...">more</a>
<div class="pane inactive ...">
...
</div>
</div>
<div class="container">
<a class="toggle-btn ...">account</a>
<div class="pane inactive ...">
...
</div>
</div>
<div class="container">
<a class="toggle-btn ...">search</a>
<article class="pane inactive ...">
...
</article>
</div>
</header>
Now your JavaScript can be:
$(document).ready(function() {
$('.toggle-btn').click(function() {
var $pane = $(this).closest('.container').find('.pane');
if ($pane.hasClass('inactive')) {
$('.container .pane').addClass('inactive');
$pane.removeClass('inactive');
} else {
$pane.addClass('inactive');
}
});
});
Notice how you only need one event handler registered. Inside the event handler this references the button that was clicked. The "pane" element is found by first using .closest() to get the container element and then .find().
jsfiddle
So I'm using classes to sort different content, but I'm not actually sure how to apply this sorting.
<div class="class1"><div class="heads">Title</div>
<div class="description"><p>Class 1 Item 1</p></div></div>
<div class="class2"><div class="heads">Title</div>
<div class="description"><p>Class 2 Item 1</p></div></div>
<div class="class2"><div class="heads">Title</div>
<div class="description"><p>Class 2 Item 2</p></div></div>
<div class="class3"><div class="heads">Title</div>
<div class="description"><p>Class 3 Item 1</p></div></div>
So let's say the user clicks a button that says 'Class 2'. I want the opacity of everything that is not class 2 to be, say, .5 while class 2's opacity stays at 1. I've tried using .not(), but I'm not familiar with it and most examples use it in conjunction with .siblings(), and I don't want the siblings to fade either. Help? I'm not sure what to do.
Edit: Sorry about the orphan s. ^_^; Fixed them!
http://jsfiddle.net/orjj65g0/7/
$("#container button").click(function() {
var className = $(this)[0].className;
$("#container button").each(function() {
if($(this)[0].className !== className) {
$(this).next().addClass("op05");
$(this).next().removeClass("op1");
} else {
$(this).next().addClass("op15");
$(this).next().removeClass("op05");
}
});
});
With $("#container button").click(...) you access every button in #container.
$(this).[0].className is the class name of the button you have clicked.
After you have clicked the button, you go through every button in the container:
$("#container button").each(...)
In the container you compare the class names with the clicked class name. If there are not the same, than add the class "op05" to the div after the button and remove the class "op1" from the div after the button:
(Example:
<button class="classN">click</button>
<div class="content">div after button</div>
$(".classN").next()...
)
Here:
$(this).next()...
And with all the div's after the button(s), that have the same class name happens the same with the 'opposite' class names.
$("div").not(".class2").css("opacity", "0.5")
will set opacity of all divs except for ones with class class2 to 0.5.
If you are using a container:
$('.container>div:not(.class2)').css('opacity', 0.5);
1. You have invalid HTML. a tag opening is missing. Based on my assumptions, that's how it should look like:
<div class="classX">
Title
</div>
<div class="description">
<p>Class X Item 1</p>
</div>
But it's very unintuitive syntax. What is .description content for? I suggest you to rewrite syntax. For example:
<div class="classX">
Title
<div class="description">
<p>Class X Item 1</p>
</div>
</div>
2. You can use .not() method or :not() selector in jQuery
According to my version of HTML. Let's code!
$("a").on('click', function(){
var $t = $(this).parent(); // clicked div.class2 for example
$t.css("opacity", 1).siblings().css("opacity", 1); // undo selection
$t.siblings().not("."+$t.attr("class")).css("opacity", 0.5);
// hide other classes. Equivalent with selector:
//$t.siblings(":not(."+$t.attr("class")+")").css("opacity", 0.5);
});
Check it that's what you want: http://jsfiddle.net/Tymek/2k85m8r9/
I am very new to JS. My requirement is very simple, to change the color of Text on Mouse Over.
I have created 2 JS functions : 1st for MouseOver and 2nd for MouseOut.
Can I do it in one single JS function.
I have other Text also.
JavaScript
function highlightBG(element) {
document.getElementById('element').className='AttachOnMouseOverText';
}
function highlightOutBG(element){
document.getElementById('element').className='AttachOnMouseOutText';
}
HTML code :
<td align="center" id="element">
<img name="folder" onMouseOver="highlightBG();return true;" onMouseOut="highlightOutBG();return true;">
<br>Add Folder
</td>
You can find here the answer using pure-js as you asked :
HTML :
<div id="element" class="AttachOnMouseOutText" onMouseOver="highlightBG();return true;" onMouseOut="highlightOutBG();return true;">Hidden text</div>
CSS :
.AttachOnMouseOverText {
color: white;
}
.AttachOnMouseOutText {
color: black;
}
Javascript :
function highlightBG() {
document.getElementById('element').className='AttachOnMouseOverText';
}
function highlightOutBG(){
document.getElementById('element').className='AttachOnMouseOutText';
}
You can see here an example using CSS :hover state.
EDIT
If you want a single function to handle this, try someting like :
function highlightBG(elementName, isIn) {
if (isIn)
document.getElementById(elementName).className = 'AttachOnMouseOverText';
else
document.getElementById(elementName).className = 'AttachOnMouseOutText';
}
this is simple by using css:
selector:hover
{
color:red;
}
And you can also use jquery for this
$("selector").on( "mouseover", function() {
$( this ).css( "color", "red" );
});
If you need the hover change on a link then definitely use a :hover in CSS, it will be the most efficient way.
However if you are looking to add it to a non-link element it can cause issues in IE7 and 8. Have a look at Google Best Practices, in particular the section about :hover.
If that is the case then JS is a way to do it.
It might be easier to use jquery to do what you want, if you are using javascript you might just as well make use of jquery. Create a css class to represent the color you want to change the text to, for example
.green{
color: green;
}
Change your HTML to
<td align="center" id="element">
<img name="folder" />
<br>Add Folder
</td>
And add some jquery to add your css class when you move your mouse over 'element', for example
$("#element").mouseover(function(){
$(this).addClass("green");
});
If you want to change the color back when the mouse leaves the area, you can just remove the class again. For example
$( "#element" ).mouseleave(function() {
$(this).removeClass("green");
});
Here is the HTML (with an inline ID of "practice"):
<h1 id="practice">Hello!</h1>
Here is the vanilla JavaScript (using a generic function and a callback):
document.getElementById("practice").addEventListener("mouseover", function() {
document.getElementById("practice").style.color = "pink";
});
document.getElementById("practice").addEventListener("mouseout", function() {
document.getElementById("practice").style.color = "yellow";
});
Mousing over changes the HTML text to yellow; removing the mouse from the area returns the HTML text to black.
I want to display only div.card1 when a user clicks on a selection menu I have made
<table id="flowerTheme">
<tr>
<td>
<div class="card1">
<div class="guess"><img src="Test Pictures/QuestionMark.gif" /></div>
<div class="remember"><img src="Test Pictures/flower.gif" /></div>
</div>
</td>
<td>
<div class="card2">
<div class="guess"><img src="Test Pictures/QuestionMark.gif" /></div>
<div class="remember"><img src="Test Pictures/flower.gif" /></div>
</div>
</td>
</tr>
</table>
I have a function that toggles the class 'selected' when the user clicks on an image. The following works perfectly:
if($('.flowerThemePic').hasClass('selected') && $('.sixCardLayout').hasClass('selected')) {
$('#flowerTheme').css('display', 'inline');
However, as I stated before, I would like to have card2 to not be displayed. I have tried:
if($('.flowerThemePic').hasClass('selected') && $('.sixCardLayout').hasClass('selected')) {
$('#flowerTheme').not('.card2').css('display', 'inline')
But this does not do anything. I have also tried:
if($('.flowerThemePic').hasClass('selected') && $('.sixCardLayout').hasClass('selected')) {
$('#flowerTheme').find('div').not('.card2').css('display', 'inline')
But this hides both cards. What would be the right method of displaying card1 and not card2?
$('#flowerTheme').css('display', 'inline');
$('.card2').hide();
First of all, it looks to me that card1 and card2 should be id, not class. The difference is that IDs are supposed to be unique, while classes are supposed to be re-used. Since you're using card1 and card2 to uniquely identify those cards, they should be IDs. Furthermore, they probably need a class as well: probably class="card", so they can be referred to as a group.
Secondly, I think you should be using CSS, not jQuery for the actual hiding/showing. Consider this:
table#flowerTheme.selection-made :not(.selected) .card
{
display: none;
}
This would hide any element that has class="card" that doesn't have any parent with class="selected". Note the .selection-made on #flowerTheme -- this allows the default case to show every card, but then when someone clicks, you do $('#flowerTheme').addClass('selection-made'); and then $(this).addClass('selected'); (assuming you're using $(wherever selected goes).click() for this). It's a bit unclear from your question exactly where the selected class is being added, but I'd recommend doing it this way. It is far more easily maintained, jQuery has to do less work, and it leaves you with a very simple and easy way to expand the list of cards.
What about :
$('#flowerTheme .card2').hide();
?
You can write a javascript function to hide children...
function hideSpecificChildren(childClass){
var child = document.getElementByClass(childClass);
if(tab.style.display == "block") {
tab.style.display = "none";
}else {
tab.style.display = "block";
}
}
Try this:
$('#flowerTheme .card2').css('display','none').parent().show();
Demo
OR
$('#flowerTheme .card2').hide().parent().show();
Demo