My code is:
<div id="post">
Delete
<b>Admin</b> says:
"Hi to all my frends!"
<br>
7 hours ago ·
<a id="like" href="./?act=like&id=13" title="No one likes">Like</a> ·
<a id="dislike" href="./?act=dislike&id=13" title="No one dislikes">Dislike</a>
</div>
I also have multiple posts like this one above... How can i make with jQuery that every time I "mouseover" #post, the #remove inside that #post appears?
First I think you want to use class="post" and class="remove" if you have multiple posts like that one. Then you can do it like this (the code on jsfiddle):
$(".post").on("mouseover", function(){
$(this).find(".remove").show();
}).on("mouseout", function(){
$(this).find(".remove").hide();
});
Some jQuery functions you might want to look into: .on(), .mouseover(), .mouseout(), .hover().
I made an example for you:
http://jsfiddle.net/BumbleB2na/a5vuD/1/
You want to use classes instead of IDs to support multiple posts. Also, you should hide your "remove" elements on startup.
Related
I've spent far too many hours trying to figure this out and as JavaScript is not my primary language and not yet a jQuery guru I've determined I need to ask for help.
In a case where a generated page has a structure where it has a DIV for some odd reason no ID, multiple non-standard data tag attribute tags, but at least standard style CLASS assignment....however...it has been assigned MULTIPLE classes.
Now, just one of those style classes is such that it has a code event associated that I want to neuter and leave all other classes still assigned. What I've tried there (this list is far from complete I have tried many things):
document.getElementsByClassName('Goodclass01')[0].remove('BADCLASS');
document.querySelectorAll('[data-tag-one="["value",
"value"]"]').remove('BADCLASS');
Various jnode calls that all fail due to claims of being unknown
A couple variations of something referred to as the "location hack" none of
which I could get to work but may have very well have been user error.
Safewindow attempt to just replace BADCLASS javascript function all together
but not ideal explained below.
Here is an example of the kind of structure of the target:
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one="["value", "value"]">
</div>
In this example there is a javascript function that fires upon clicking the href link above due to the function being associated with BADCLASS style assignment. So, from lots of searching it seemed like I should be able to grab that DIV by any of the initially assigned classes (since there is unfortunately not a class ID which would make it very easy) but then reassign the list of classes back minus the BADCLASS at page load time. So, by the time the user clicks the link, the BADCLASS has been removed to look like this:
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03"
data-tag-one="["value", "value"]">
</div>
I also read that simply using unsafewindow to replace the BADCLASS javascript function could be possible, so I am open to hearing one of you gurus help with how easy (or hard) that would be. In a case where BADCLASS could be shared function code perhaps called by another element on the page still having that initial class that perhaps we desire to continue to function which is why if it is only a single element that needs to be altered, I would rather just change this one href div.
Hope the explanation makes sense and what is probably a laughable simple example above for the Javascript gurus so forgive me but your help is greatly appreciated and will save more hair pulling! :)
EDIT: This must work above all in Chrome browser!
Remove the class from all elements
If you want to remove the class from all elements that have the class, simply select all of the elements with that class and remove the class from their class lists.
[...document.querySelectorAll('.BADCLASS')]
.forEach(e => e.classList.remove('BADCLASS'));
const elements = [...document.querySelectorAll('.BADCLASS')];
elements.forEach(e => e.classList.remove('BADCLASS'));
console.log(elements);
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>link</a>
</div>
Using jQuery:
$('.BADCLASS').removeClass('BADCLASS');
const elements = $('.BADCLASS');
elements.removeClass('BADCLASS');
console.log(elements);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>link</a>
</div>
Remove the class from a subset of elements
If you only want to remove the class from a subset elements, select those elements then from the class from their class lists.
[...document.querySelectorAll('.Goodclass01, .Goodclass02, .Goodclass03')]
.forEach(e => e.classList.remove('BADCLASS'));
const elements = [...document.querySelectorAll('.Goodclass01, .Goodclass02, .Goodclass03')];
elements.forEach(e => e.classList.remove('BADCLASS'));
console.log(elements);
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>link</a>
link
</div>
Using jQuery:
$('.Goodclass01, .Goodclass02, .Goodclass03').removeClass('BADCLASS');
const elements = $('.Goodclass01, .Goodclass02, .Goodclass03');
elements.removeClass('BADCLASS');
console.log(elements);
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>link</a>
link
</div>
Run at document idle
The default for the run-at directive is document-idle, but if for some reason that has been changed, either it needs to be document-idle, or you need to otherwise delay execution of the script until the document has loaded.
You could use the run-at directive in the userscript header like so:
// #run-at document-idle
Or attach a load event listener to the window
window.addEventListener('load', function() { /* do stuff */ }, false);
Include jQuery
If you're using one of the jQuery solutions, you will have to include jQuery using the require userscript header directive like so:
// #require https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
Got it with the help of both of the clear, awesome correct answers below that literally came in within seconds of each other and only a few min after my post, so thanks to both #Tiny and #Damian below!
I'm upvoting both as they both listed the same correct jQuery answers, and Tiny also provided the pure JS.
I am posting the full answer below because without the other steps, with Tamper/Greasemonkey neither will produce the desired results.
First, Tamper/Greasemonkey do not load jQuery by default, so it is just easy as add #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js to your current script and also put this.$ = this.jQuery = jQuery.noConflict(true); to avoid any versioning conflicts.
Also, in this case unfortunately I HAD to change my TamperMonkey header to:
// #run-at document-idle
along with the above mentioned:
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
and begin the script with:
this.$ = this.jQuery = jQuery.noConflict(true);
and finally the primary accepted/best answer in this case of:
$('.Goodclass01').removeClass('BADCLASS');
NOTE: The above #run-at line is required, and since so many (all) of my current Tamper/Greasemonkey scripts are actually set by default to run at START, this is of importance as it means functions like this must be separated to their own scripts to run instead AFTER the page loads (idle). Once this is added, even the above pure JS answer from Tiny did in fact produce the desired result.
As the simplest one-line answer that I was hoping was possible in Javascript, as it is so many other languages in a single line of code. I've used it in the past, but was not aware of this particular removeClass method.
Your question mentions jQuery. Did you want a solution in jQuery?
If so, it's as easy as:
$(".Goodclass01").removeClass("badclass");
Explanation:
jQuery can be referenced as jQuery() or $(). The parameters you can pass are: 1, a Selector statement (like CSS), and 2, context (optional; default is document).
By stating $(".Goodclass01") you are stating, "Give me a jQuery object with all elements that have the class Goodclass01." Then, by using the removeClass() function, you can either pass it no parameters and it would remove all classes, or you can pass it specific classes to remove. In this case, we call .removeClass("badclass") in order to remove the undesired class.
Now, if you need to select only specific elements, such as links that have Goodclass01, you can do:
$("a.GoodClass01").removeClass("badclass");
Or, if you want to select anything that has Goodclass01, but NOT Goodclass02, you can do:
$(".Goodclass01:not(.Goodclass02)").removeClass("badclass");
jQuery is not as intimidating as it looks. Give it a shot!
Edit: I also noticed you were trying to capture a link with maybe a specific property. You can use the [property] syntax to select elements that have a specific property. Most typically, people use $("a[href^=https]") or something to that effect to select all a tags with the property href that begins with ^= the string https.
You could, in your case, use the following...
$("a[data-tag-one]")
... to select all links that have the property data-tag-one.
Note: One thing to keep in mind is that, a jQuery object is different than a pure DOM element. If you have a collection of multiple elements and want to use a pure JavaScript function on one element in particular, you would have to reference it with either [0] or .get(0). Once you do that, you will no longer be able to use jQuery methods until you convert it back to a jQuery object.
But, since jQuery has a whole slew of methods to use to make DOM manipulation easier, you can probably accomplish what you need to using those methods.
Edit: I've included a snippet below so you can see some of the jQuery selectors in action.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
div#main * { background-color: #66ff66; }
div#main .BADCLASS, div#main .BADCLASS * { background-color: #ff8888 !important; }
</style>
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>All classes and data-tag-one</a><br />
<a href="SOME LINK" class="Goodclass01 BADCLASS" data-tag-one='["value", "value"]'>Goodclass01 and data-tag-one</a><br />
All classes, no data-tag-one<br />
<a href="SOME LINK" class="BADCLASS" data-tag-one='["value", "value"]'>Just BADCLASS and data-tag-one</a><br />
<br />
<table class="Goodclass01 BADCLASS"><tr><td>Here is a table</td></tr><tr><td>with Goodclass01 and BADCLASS</td></tr></table>
</div>
<hr>
<div id="buttons">
$(".Goodclass01").removeClass("BADCLASS");<br />
$("a.Goodclass01").removeClass("BADCLASS");<br />
$(".Goodclass01:not(.Goodclass02)").removeClass("BADCLASS");<br />
$("a[data-tag-one]").removeClass("BADCLASS");<br />
Reset the HTML<br />
</div>
<script>
$("#button1").click(function(){
$(".Goodclass01").removeClass("BADCLASS");
});
$("#button2").click(function(){
$("a.Goodclass01").removeClass("BADCLASS");
});
$("#button3").click(function(){
$(".Goodclass01:not(.Goodclass02)").removeClass("BADCLASS");
});
$("#button4").click(function(){
$("a[data-tag-one]").removeClass("BADCLASS");
});
$("#button5").click(function(){
var str = '<div class="main_content" data-tag-id="12345">Some stuff sits above</div>All classes, no data-tag-one<br /><a href="SOME LINK" class="BADCLASS" data-tag-one=\'["value", "value"]\'>Just BADCLASS and data-tag-one</a><br /><br /><table class="Goodclass01 BADCLASS"><tr><td>Here is a table</td></tr><tr><td>with Goodclass01 and BADCLASS</td></tr></table>';
$("div#main").html(str);
});
</script>
I have implemented some buttons on a web page that show and hide some text based on which button the user clicks:
Please bear in mind that the .reveal-1 fragment is set to display:none in the CSS by default.
http://bestclownintown.co.uk/ct/bootstrap-3.3.7/docs/examples/CT_task/index.html
HTML:
<div class="media">
<div class="media-left"> <img alt="New delivery options" class="media-object" src="images/thumbnail-new-delivery-options.jpg"> </div>
<div class="media-body">
<h4 class="media-heading">Cotton Traders Introduces New Delivery Options</h4>
<p class="text-muted">14th January 2016</p>
<p>Cheshire based retailer, Cotton Traders, has added three new delivery options to its e-commerce offering, in order to improve the customer shopping experience.</p>
<a class="btn btn-default reveal-button-1" href="#" role="button">Read More <i class="fa fa-caret-down" aria-hidden="true"></i></a>
<div class="reveal-1">
<p>The casual clothing retailer now offers its UK customers a choice of standard, next day, Sunday and nominated delivery options.</p>
<p>With more delivery options to choose from, customers will benefit from this added convenience, allowing them to get their items quicker and at a time that suits them, for as little as £3.99.</p>
<p>Talking about the introduction, Supply Chain Director, Caroline Allerton, said: "As a company we are constantly striving to improve the offering for our customers and this includes the delivery options.</p>
<p>"We know that our customers all have busy lives, so the introduction of these options will fit into their schedule and allow them to get their orders when they need them."</p>
<p>The introduction comes after Cotton Traders launched its dedicated Australian e-commerce website earlier this year.</p>
<a class="btn btn-default hide-button-1" href="#" role="button">Read Less <i class="fa fa-caret-up" aria-hidden="true"></i></a>
</div>
</div>
</div>
JS:
$(".reveal-button-1").click(function(){
$(".reveal-1").show();
});
$(".reveal-button-1").click(function(){
$(".reveal-button-1").hide();
});
$(".reveal-button-1").click(function(){
$(".hide-button-1").show();
});
$(".hide-button-1").click(function(){
$(".reveal-1").hide();
});
$(".hide-button-1").click(function(){
$(".hide-button-1").hide();
});
$(".hide-button-1").click(function(){
$(".reveal-button-1").show();
});
1) So in the first call to the jQuery object we show the <div> with a class of .reveal-1 when .reveal-button-1 is clicked
2) Then we hide .reveal-button-1
3) We then show .hide-button-1 when .reveal-button-1 is clicked
Now the hide button is present in the DOM.
4) We hide the <div> with a class of .reveal-1 when .hide-button-1 is clicked
5) We hide .hide-button-1
6) Finally we show .reveal-button-1 again.
Are there any solutions I can apply to refactor my JavaScript, so that I am not calling to the jQuery object as often and repeating myself so many times. I am aware of the .toggle method but I am not sure that it can be applied in this case. Please give a thorough explanation with your answer as I need to understand the jQuery logic. I have tried to keep the jQuery logic as simple as possible as I am only of a junior level.
I currently have 24 lines of jQuery code for 4 HTML fragements which seems quite excessive, but I don't know if there is a better way to implement/optimise.
here it is,
On any button click all element toggles visibility. its exactly what you need.
$(".reveal-button-1, .hide-button-1").click(function(){ //on click of either button.
$(".reveal-1, .reveal-button-1, .hide-button-1").toggle(); //toggle visibilty on all the corresponding elements
});
Make sure your initial values (display:none) are correct.
reveal button click will hide itself, show the hide button and toggle the reveal field (to show).
since the hidden button is now visible and the reveal button is no longer. once we click on this button the field will toggle (to be hidden again). the reveal button will be visible again.
side note: You probably want to use better css classes in your html though. (to make a more generic javascript code so that you can re-use its functionality).
re-usable solution
here is a re-usable version, with better classes.
$('.toggle-btn').click(function(){
$(this).closest('.container').find('.toggle').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="toggle-btn toggle" style="display:none;">show</div>
<div class="toggle-btn toggle">hide</div>
<div class="toggle">bla bla</div>
</div>
<div class="container">
<div class="toggle-btn toggle" style="display:none;">show</div>
<div class="toggle-btn toggle">hide</div>
<div class="toggle">bla bla</div>
</div>
Explanation: when a toggle-button is clicked. it goes and finds the first parent that has a class .container. then from this parent, it checks all the html elements with the .toggle class inside this container and toggles their visibility.
Side note on this solution: it is not a very prerformant solution because every time it tries to find the container class in its parents and then tries to find all the childs with class toggle. (better is to cache these classes). but for this simple solution it doesn't really matter.
out of the box libraries
bootstrap collapse
jquery accordion
You only need one event handler for each element. Repeating like that causes a lot of extra functions to be called on each event, which will slow your site down. (Probably not noticeably, but if your site grows it could become problematic.)
If your HTML is structured similarly for each of your sections, you could eliminate the specific classes, and go on a more general approach. (Shortened for brevity.)
<a class="... reveal-button"...>
<div class="reveal">
...
<a class="... hide-button"...>
</div>
Then down inside your JavaScript, instead of 4 sets of all your calls, you can do just a single. I'll explain how this works as we go. The function .on() is the preferred method to wire events since jQuery 1.7.
$('.reveal-button').on('click', function () {
var $self = $(this); // 'this' will be the element that was clicked.
$self.next('div.reveal')
.show();
$self.hide();
});
$('.hide-button').on('click', function () {
var $parent = $(this).parent(); // refers to div.reveal
$parent.hide(); // hide the div
$parent.prev('a.reveal-button').show(); // show the reveal button.
});
I am very new to jQuery and not entirely sure what I'm doing. Will try my best to explain the problem I'm facing.
I'm trying to lock some content on a landing page until a user shares the link using FB, Twitter, LinkedIN or G+. The first version of the script I wrote (which worked fine) ran like this:
<head>
<script type="text/javascript">
...
$(document).ready(function()
{
$('.class').click(clearroadblock());
buildroadblock();
}
</script>
<style>
.class
{
[css stuff]
}
</style>
</head>
<body>
<div id="something">
<ul>
<li> Link1 </li>
<li> Link2 </li>
</ul>
</div>
</body>
The problem I'm now facing is changing out this code to replace the list elements with social share buttons. As they are no longer under .class, but classes like fb-share-button and twitter-share-button. Please help me understand what I need to modify to accommodate this? PS: This is not a Wordpress site.
function clearroadblock()
{
$('#roadblockdiv').css('display', 'none');
$('#roadblockBkg').css('display','none');
}
This is the way I'm clearing the overlay once a click is detected, BTW.
Can I wrap the social buttons in divs, assign them IDs and use those IDs to trigger the click like below?
<div id="Button">
Tweet
</div>
$('#Button').click(clearroadblock());
You can have multiple classes on an element by separating them with a space. Try the following:
class="class fb-share-button"
Your jquery will still work off the "class" class. I would recommend you change this name to something more meaningful though. Your css can target the "class" for general styles, but you can also target fb and twitter separately.
Update
I decided to create a quick JSFiddle for this.
Some of the styles etc won't be the same as what you're doing, but the problem is resolved. I've created a div with id main that contains the content that you want to hide. There's an absolutely positioned div over the top of this, this is the roadblock. The javascript is showing the roadblock (assuming that's what you wanted to do with buildroadblock()).
On click of a link in the ul with id socialMedia we call clearroadblock. Notice the lack of parenthesis. This hides the roadblock.
This isn't a great way of preventing someone from seeing information, you might want to think about pulling the content down from the server when the action is performed, however, I think this answers your question.
I want to change the text of a link using javascript. The problem is this particular link does not have an id. I am unable to change the html, as this is a SharePoint page, and this particular link is created by a page layout, which I do not have access to. Using IE Developer Tools, I see that the HTML surrounding the link is this:
<span id="DeltaPlaceHolderPageTitleInTitleArea">
<span>
<a href="#ctl00_PlaceHolderPageTitleInTitleArea_ctl00_SkipLink">
<img width="0" height="0" style="border-width: 0px;" alt="Skip Navigation Links" src="" /></a>
<span>
<a title="State-Compliance" href="/sites/tax/Compliance/SitePages/State-Compliance.aspx">State-Compliance</a>
</span>
<a id="ctl00_PlaceHolderPageTitleInTitleArea_ctl00_SkipLink"></a>
</span>
The link I wish to change is the second one, the one with "State-Compliance" for the tooltip.
I looked at jQuery, and found I could use $('#DeltaPlaceHolderPageTitleInTitleArea').find("a").text("Test"); to change the text, but it changes the text of all three links. How can I change just the one? Do I need to iterate through the three, or is there an easier way of getting the link I wish to change?
Sorry if this is a stupid question, I'm a c# developer, and this is my first experience using javascript.
Let me know if you need more information.
Warren
Use .eq():
$('#DeltaPlaceHolderPageTitleInTitleArea').find("a").eq(1).text("Test");
jsFiddle example
How about this, using the attribute equals selector:
$('#DeltaPlaceHolderPageTitleInTitleArea a[title="State-Compliance"]')
Just another Rails newbie with a problem.
I have some Javascript (dynamic) in a partial .html.erb, but I have been informed in another post that this is really not where the Javascript should go. It's dynamic so I can find the correct ID of an element and only apply the javascript on that particular element. I assume it is possible to parameterise the javascript and put it in an external file and somehow call it from my partial. Would that be the correct way to do it? If so how would I do that? If not what should I do?
I have a nested resource. On the parent resource's show I am using AJAX to add children without leaving this page. I have quite a lot of Javascript magic that needs to be executed for each added child.
Partial _care_point.html.erb
<script>
$(function() {
$("#<%="node_#{care_point.id}" %>").live('dblclick', function(){
console.log('moo');
jQuery(this).hide();
jQuery('.close', jQuery(this).parent()).show();
jQuery('.node_input', jQuery(this).parent()).show();
});
});
</script>
<div id=<%="care_point.#{care_point.id}" %> class='draggable node_chin'>
<div id=<%="node_#{care_point.id}" %> class='node'><%= care_point.body %>
</div>
<textarea class='node_input'><%= care_point.body %></textarea>
<a class='close' href='#'>Close</a>
</div>
Thanks,
Erik
In your partial:
<div id=<%="care_point.#{care_point.id}" %> class='draggable node_chin care_point'>
<div id=<%="node_#{care_point.id}" %> class='node'><%= care_point.body %>
</div>
<textarea class='node_input'><%= care_point.body %></textarea>
<a class='close' href='#'>Close</a>
</div>
In public/javascripts/application.js (where your js should be)
$(function() {
$(".care_point").live('dblclick', function(){
console.log('moo');
jQuery(this).hide();
jQuery('.close, .node_input', jQuery(this).parent()).show();
});
});
Having used rails for a few years, I have never had to generate JS dynamically in the view. I can't think of a good use case that would require this (if you can think of one, leave a comment please).
I've had similar cases where I need to reference the DOM element by ID (for example, a custom library that expects an ID as a parameter). What I normally do in these cases is generate inline javascript as Erik points out, or a more hybrid solution is adding a class, then cycle through all elements of that class, get their IDs, and bind them to the respective event (or do whatever you need with the ID).
I'd also like to see a best practice for this…