Selecting an HTML element by it's ID attribute with jQuery - javascript

I picked up some code on CodePen to help me dynamically replace the content of divs. It works, but as often happens when borrowing someone's code, I can't actually mold it to what I want it to do.
The original code provides pictures of animals, and when you click it, it sends the text of the name of the animal to a div. The Javascript looks like this:
$('#kittens').click(function() {
$('div').html('Kittens');
});
$('#aardvark').click(function() {
$('div').html('Aardvark');
});
I'm applying it to a more complicated webpage, so I really can't have it just replace the first level div with the word "Kittens."
I've found that by keeping the single quotes, I can put any text or code I want in there and it works just fine, but only if I'm writing to the first level div.
So I figure to target it, I should just give it the div ID. Something like:
$('#kittens').click(function() {
$('myDivName').html('Kittens');
});
This does nothing. I've also tried 'id=myDivName' , 'id="myDivName"' , id: myDivName , and a few others I can't recall right now. Nothing I can come up with seems to work.
Does anybody know how this parameter works and how I can get it to target just the div I want?

jQuery selectors work just like CSS selectors, so instead of $('myDivName'), do $('#myDivName')

when referencing an element in jquery, you need to use it's css selector. For an element with an id "myDivName" that selector would be #myDivName so your jquery would look like:
$('#kittens').click(function() {
$('#myDivName').html('Kittens');
});

Related

Line clamping using a class element and Javascript

I have a PHP script that outputs data. It is all conveniently wrapped inside a p class.
It outputs the same data and same class multiple times, so there are like 6 blocks of text, each block being wrapped inside p class.
I need to reduce each block to 3 lines using any method possible. I already tried using PHP in various ways to no avail.
I came across Clamp.js which looked great. The only issue is, it will only work using ID. I can change the p class tags to p id, however, they'd all have to share the same ID, which, obviously, won't work.
Here's the current code I've tried:
var module = document.getElementsByClassName("clampjs");
$clamp(module, {clamp: 1});
And the HTML (times 6):
<div class="headtab">
Forum title<p class="bold">Posted By:</p> username <p class="bold">In:</p> category</div>
<div class="maintext">
<p class="clampjs">TEXT I WANT TO BE CLAMPED</p>
</div>
Like I say, it works fine when I use an ID, but obviously, only for the first block of text as the ID HAS to stay the same, that's why I'm using p class.
Sadly, what I've tried above doesn't work at all. Does anybody know a little fix for this script, or perhaps a different script that will clamp objects using a class element? Jquery is acceptable too.
Jsfiddle
Working code thanks to the accepted answer:
$(document).ready( function() {
$('.clampjs').css({ //changes the css of the clicked content.
'max-height':'75px', //give what ever height you want.
'overflow':'hidden'
});
});
this could be easily done with just editing your css
$('.clampjs').click( function() {
$(this).css({ //changes the css of the clicked content.
'height':'100px', //give what ever height you want.
'overflow':'hidden'
});
});
just now tested in my page it works...

Script affecting all images instead of only images in div that contains certain text (jQuery)

I've tried editing this code a number of ways (using if statments and each statements) with nothing working. The idea is so simple; if a div contains this specific text, I want to change the src attribute of the image in that div only.
I can't seem to figure out what I'm missing. The code below changes all the images in all divs with that class rather than just the ones that contain the specific text. I've tried to work in 'this' but apparently don't understand how it affects the function.
$(document).ready(function(){
$('.my-content').filter(':contains("Top")').find('img').attr("src", "http://www.samplestuff.com/kids/test.png");
});
Could someone kindly point me in the right direction of what I need to change to make the script target only images in the div that contain the text instead of all div with that class because one of the div did contain that text (I think that's what triggers it; I may be off about that too).
Try this:
$(document).ready(function(){
$('.my-content:contains("Top")').find('img').attr("src", "http://www.samplestuff.com/kids/test.png");
});
See jQuery :contains docs
Edit
Actually I think your answer should work as well. Seems to work fine in this jsfiddle, can you post your markup?
$('div').filter(':contains("Top")').css("color", "red")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Top</div>
<div>Right</div>
<div>Bottom</div>
<div>Left</div>

Can you use a jQuery selector on a HTML tag that a JS string printed?

Sorry if the question was misleading, I couldn't find a better way to describe my problem. Anyway, here goes:
Suppose I had a button start that initially displays a string for me. Said string (let's call it stringA) is output through jQuery like this:
$(".start").click(function() {
$(".startButton").hide('slow', function() {
$("#table1").html(stringA);
});
});
Alright. Cool. That worked without a hitch. Now inside stringA I have multiple
<span class="optButton">this is a button</span> buttons. I have another onClick handler for my optButton button, and it goes like this:
$(".optButton").click(function() {
alert("Testing");
$("#table1").html(stringB);
});
Needless to say, clicking on optButton is supposed to replace the contents of #table1 with stringB. However, when I tried it, it doesn't work. I tried adding alert() to test and see if jQuery managed to select optButton, but it seems that it didn't because I get no popup from the alert() function.
My theory is that since optButton was not part of the original HTML and is within a string stringA, jQuery is unable to select optButton as a result. If this is true, is there a workaround to this issue? If it is not, what is the actual cause of the problem here?
You need to use event delegation since your span element has been dynamically added to the DOM:
$('#table1').on('click', '.optButton', function() {
alert("Testing");
$("#table1").html(stringB);
});
This technique will helps you to attach click handler to these newly created span elements.

How can I select a block of text on a page, then move an element in front of it?

I have a div that will appear on the page at a separate point. It doesn't always appear on the page and can be added via a CMS if needed. There's a line of text that will appear within the body. If the user has decided to have this div added, it would need to be moved into position via jquery. So, I have this text:
<p><strong>Key Facts:</strong></p>
I want to find it using jquery, then move the other div in front of it. I tried a couple of different ways to select this text then move the div in front of it and haven't had any luck. The best way I found to find the text was to do this:
var foundin = $('*:contains("<p><strong>Key Facts:</strong></p>")');
From that point, to move the div into position, I thought I could something like this:
$('#DivIWantToMove').insertBefore($foundin);
That didn't work, though. I also looked at this:
$( $foundin ).before( $('#DivIWantToMove') );
AS you might imagine, since you're reading this, that didn't work either. So, I'm asking you, is it possible to do what I want? I'm fairly constrained by the CMS that we are using. The DIV I need to move will always be someplace on the page and I have to move it. The client doesn't want to have to add a class to <p><strong>Key Facts:</strong></p> so I'm let with this. If I could have a class on <p> then it would be super easy. I've already done it. The client doesn't like having an extra step. Any ideas?
I think contains selector only looks for text, not html tags. so you have to modify your contains selector. if your html is like this -
<div>
<p><strong>Key Facts:</strong>
</p>
</div>
<div id="move">something something</div>
and you want to move your <div id='move'> in front of p, then try this -
var foundin = $('p:contains("Key Facts")');
var divtomove = $('div#move');
foundin.before(divtomove);
Demo
Update also look into this QA: jQuery :contains with html. Instead of using contains you can use one of the methods from there.

How to use onmouseover?

I have a list being displayed on a JSP. On mouse hover on any of the value i need to show a description corresponding that value. Need to show description not as an alert and also cannot make the values as hyperlink.
eg.
suppose the value is ABC so on mouse hover should show AppleBoyCat.
need to use onmouseover. let me know how to do it..
What do you want to do? If you just want to show a tooltip, you can set the title attribute of any element and it will be displayed as a tooltip.
Also, the abbr tag can be used as tooltips too:
<abbr title="test">stuff</abbr>
You can go about it in two ways:
1 - a hidden dom object (a div for instance) which reveals itself when you roll over whatever
or
2 - you can rewrite the html of the particular element you're mousing over.
You can load this data in when you load everything else (either as Javascript objects, or as markup, though that's much bulkier) or you can asynchronously load the description data from a service when you mouse over (though you'll have more lag).
jQuery is a quick and dirty way to achieve this (more quick than dirty), but straight JS or pretty much any other JS library will do as well.
Perhaps not the cleanest solution but something like this:
<a class='hover' rel='tooltip'>Link</a>
//Some hidden div, putting css inline just for example
<div id='tooltip' style='display:none;'>Content</div>
$(function() {
$('.hover').mouseover(function() {
var tooltip = $(this).attr('rel');
$('#' + tooltip).fadeIn();
});
});
And offcourse add a callback hiding it again. It just takes the value from rel of the link and use as an id for the div to show.
This is a quick and dirty solution, can be made alot smoother if you just work with it a little;)
There also alot of plugins out there allowing the same functionality in a cleaner fashion.
*Edit: Just noticed you added a comment on another post that you can't use jQuery.. shouldn't tag a post with something you're not intending to use.
As TJHeuvel already said, you can simply use the title attribute.
Best approach is to build the list with both the value and title attribute from within JSP, if not possible for some reason, you can build client side array of each value and its corresponding description then using JavaScript dynamically assign the title on mouseover.
Show us some more code to get more/better help.
For simple tooltips, the title attribute is most effective, as pointed out by TJHeuvel
If you need more advanced tooltips with HTML and CSS formatting, I'd suggest you use an external library.
One that works nicely without jQuery ist wz_tooltip download here, documentation here
When included correctly, you can add tooltips by calling the functions Tip() and UnTip() as follows:
Homepage

Categories

Resources