In jQuery, how can I get text to toggle when the user hovers over an image?
I have code that changes the text when the user hovers:
# HTML
<table id="support-people">
<tr>
<td><img data-bio="Bio 1" src="person1.jpg" alt="Person 1"/></td>
<td><img data-bio="Bio 2" src="person2.jpg" alt="Person 2"/></td>
</tr>
<tr><td colspan="2">
<p id="support-person-description">Default text</p>
</td></tr></table>
# JS
$('#support-people img').hover(function(){
$('#support-person-description').text(this.getAttribute("data-bio"));
});
But when the user moves away, the text stays the same - is there a neat way I can get it to toggle back to the original, default text?
Thanks.
Use the two functions of hover (first for mouse over, second for mouse out) then in the first save the oldtext as data on the element. Then read this value and set it in the second function:
$('#support-people img').hover(function(){
var desc = $('#support-person-description');
desc.data('oldtext', desc.text()).text(this.getAttribute("data-bio"));
}, function() {
var desc = $('#support-person-description');
desc.text(desc.data('oldtext'));
});
try :
$('#support-people img').hover(function(){
var $elem = $('#support-person-description');
$elem.data('oldText', $elem.text()).text(this.getAttribute("data-bio")); // Add text on mouse hover
},function(){
var $elem = $('#support-person-description');
$elem.text($elem.data('oldText')); // Return to default
});
Change your javascript to the following.
$('#support-people img').hover(function(){
$('#support-person-description').text(this.getAttribute("data-bio"));
}, function(){
$('#support-person-description').text('Default text');
});
You can write onMouseOver and onMouseOut functions in the same call
http://api.jquery.com/hover/
the .hover() method requires TWO parameters. On for what happens when hovering and one for when not hovering. Your code only has the instruction to display the element. You are missing the instruction to remove it again.
Related
I'm creating a button through JavaScript and am trying to assign it to an onclick event. At runtime the button is created but the onclick event isn't firing when I click it. Also in Chrome's Inspector, no error is generated when I click the button.
Here's my code:
function truncator(){
$.each($('td.rawdata-field').not(':empty'), function(i,v){
var count = parseInt($(v).text().length);
var maxChars = 650;
if(count > maxChars){
var str = $(v).text();
var trimmed = str.substr(0, maxChars - 2);
$(v).text(trimmed + '...');
var btn = document.createElement('button');
btn.setAttribute('content', 'test content');
btn.setAttribute('class', 'show-full-text-button');
btn.innerHTML = 'Show Full Log';
btn.onclick = function() {
alert("assd");
};
$(v).append(btn);
}
});
};
v is the parent container, which in this case is a td element.
What's the problem here?
EDIT:
One additional detail I can offer is that the above is being executed many times over a page, which is have something to do with why it isn't working. All the buttons are being created fine, but the alert's aren't working when done through the above method.
The container already exists when the above code is executed.
EDIT 2:
I've updated the code above to include more of what is going on. The function truncator basically is supposed to go through all td elements with class rawdata-field that are not empty, and check if the text mentioned in it is longer than 650 characters. If it is, it truncates the text to 650 characters and then puts a button there to showing the complete log if the user wishes to do so.
The table on which the above function operates already exists when truncator is called.
Your code work fine here: https://jsfiddle.net/dusfqtr9/
$(document).ready(function() {
var btn = document.createElement('button');
btn.setAttribute('content', 'test content');
btn.setAttribute('class', 'show-full-text-button');
btn.innerHTML = 'Show Full Log';
btn.onclick = function() {
alert("Hello !");
};
$("#container").append(btn);
});
Maybe your script is run before the parent container created, so $(v).append(btn) do nothing.
onclick only works with the elements that already exist at the time when the script (containing your onclick handler) is loaded. As such, elements that get created after that, are no longer bound to the onclick event that you specified in the loaded script.
I'm not sure what your full code set is, but I'm guessing that your button is regenerated probably several times after the script is loaded. This is the most likely reason why the onclick event does not fire.
As such, what you would want to do is to "attach" the event handler to a higher level in the DOM tree (highest being your html) that you are sure won't get 'programmatically' regenerated, then you'd want to check if the element in question, which is inside the DOM, exists. You then run your function when this element is found.
Below is a JQuery implementation of this logic using the .on :
EDIT1: I've edited the code based on your latest comment. You'll notice that I've separated the function that handles the click of your buttons. I urge you to try doing this in your original code set, and you'll see that the onclick event will always be bound to your buttons regardless of when your buttons are created, or even how many times you regenerate them.
EDIT2: I just noticed in the comments that you wanted to show the full text in the alert. Edited the code to show one way of doing that.
function truncator(){
$.each($('td.rawdata-field').not(':empty'), function(i,v){
var origContent = $(v).text();
$(v).attr('orig-content',origContent);
var count = parseInt($(v).text().length);
var maxChars = 10;
if(count > maxChars){
var str = $(v).text();
var trimmed = str.substr(0, maxChars - 2);
$(v).text(trimmed + '...');
var btn = document.createElement('button');
btn.setAttribute('content', 'test-content');
btn.setAttribute('class', 'show-full-text-button');
btn.innerHTML = 'Show Full Log';
$(v).append(btn);
}
});
};
$('html').on('click', '.show-full-text-button', function(){
content = $(this).closest('td').attr('orig-content');
alert(content);
});
truncator();
table td {
border:1px solid black;
padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="rawdata-field"> this is a very long text </td>
<td class="rawdata-field"> another long text </td>
<td class="rawdata-field"> this is getting out ofhand </td>
</tr>
<tr>
<td class="rawdata-field"> okay another longtext </td>
<td class="rawdata-field"> more content here, and there's another one here </td>
<td class="rawdata-field"> what am i doing here </td>
</tr>
</table>
I created new website and on it I want when I click on one div jquery show me div ID and I user this command and I can give div ID
var name = $(this).attr("id");
and when I want to give div's child I use this Command
var name = $(this).children(".select").attr("name");
now I have 3 divs like this
enter image description here
and when I click on div 3 Jquery give me div2 with this command
var name = $(this).children(".select").attr("name");
how can I get div's ID when click on it?
example click on div 1 show me div 1 or when I click on div 2 show me div 2
and when I click on div 3 show me div 3
Thanks
Your first code was correct, you don't need to find children...
$("div").click( function(){
var name = $(this).attr("id");
console.log( name );
});
If you have trouble with multiple events, you can stop propagating the click event with .stopPropagation() like so:
$("div").click( function( e ){
var name = $(this).attr("id");
console.log( name );
e.stopPropagation();
});
See example: https://jsfiddle.net/tg4rmkk9/
You've already solved the main part of the problem:
var name = $(this).attr("id");
This will get you the ID of the Div.
To alert it you can then do alert(name);
Here's a demo of what I think you're going for :
$('[id^=div]').on('click', function() {
alert($(this).attr('id'));
});
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<div id="div1">
Click me
</div>
<div id="div2">
Click me too
</div>
<div id="div3">
Click me three
</div>
(see also this Fiddle)
I'm trying to achieve something inside a function, to actually access the parent selector.
Here is a small snippet of my HTML code:
<div class="module-row module-tab pull-right" id="modtab-sql_net">
<img src="images/icons/icon-orangebox-plus.png" class="modtab-toggle">
</div>
<div id="tab-module-row-1">
</div>
<div class="module-row module-tab pull-right" id="modtab-sql_dss">
<img src="images/icons/icon-orangebox-plus.png" class="modtab-toggle">
</div>
<div id="tab-module-row-2">
</div>
Here is the jQuery script I tried:
$('div[id^="modtab-"]').click(function(){
$(this).next('div[id^="tab-module-row"]').toggle(function(){
$(this).next('.modtab-toggle').toggle_switch.attr("src").replace("plus", "minus");
// The above line is incorrect. I need to change img attr for the class which is inside the div being clicked
});
});
Now, I want to actually change the image icon from a "plus" to a "minus" (the filenames are kept such).
I need to change $(this).next('.modtab-toggle') in the code to something that can work.
Please do NOT suggest to simply access the class using $('.modtab-toggle') as I have multiple such div tags in the code. It won't work out that way.
Thanks for any help.
Try this:
$('div[id^="modtab-"]').click(function(){
$(this).find('.modtab-toggle').attr("src", function(i, attr){
var o = this.src.indexOf('plus') > -1 ? this.src.replace('plus', 'minus') : this.src.replace('minus', 'plus');
return o;
});
});
See the Demo # Fiddle
try something like this
$('div[id^="modtab-"]').click(function(){
var $this = $(this);// clicked div
$this.next('.tab-module-row').toggle(function(){
$this.find('.modtab-toggle').toggle_switch.attr("src").replace("plus", "minus");
});
});
Note: you should use class instead of id because it should be unique
#tab-module-row ->.tab-module-row
EDITED ANSWER
$('div[id^="modtab-"]').click(function(){
var $this = $(this);// clicked div
$this.next('div[id^="tab-module-row"]').toggle(function(){
var img = $this.find('.modtab-toggle'); // your image object
// your condition to check which image to display will goes here.
});
});
change $(this).next('.modtab-toggle') to $(this).find('.modtab-toggle') to make it work.
See find() docs here
I have three elements, which are sliding on the screen, i want to get the text of element which is currently showing on the screen, I tried .text() function, but this returns the text of all the s elements, is there any way using javascript or jquery to do this.
<div id="text">
<span style=" font-size:100px;text-align:center;">koko</span>
<span style=" font-size:100px;text-align:center;">abc</span>
<span style=" font-size:100px;text-align:center;">efh</span>
</div>
$(document).ready(function(){
$('#text').mouseover(function(){
var txt = $('#text span').text();
alert(txt);
});
});
demo or another here
code
$('#text > span').mouseover(function(){
var txt = $(this).text();
alert(txt);
});
Since you are using the cycle plugin, the active slide is given the class "activeSlide". You can get the text of the active slide by doing something like $('.activeSlide').text();
You can also set a callback in the options while initialising the cycle plugin. You can look at the options that you can set with cycle here: http://jquery.malsup.com/cycle/options.html
You will be able to use the "after" event callback in case you want to do something everytime the slide changes.
$(document).ready(function () {
$('#text').cycle({
after: function (currSlideElement, nextSlideElement, options, forwardFlag) {
alert($(nextSlideElement).text());
}
});
});
I have this code blow, it is use to switch an image to a second image on mouse click and also wrap a link around it at the same time. Upon clicking the image the second time it will take you to the link and also toggle back to the previous image.
What I'm trying to work out is how to also when it toggles back to the previous image is to also get rid of the wrapped link.
Also would it be possible to use the toggle on mouse click on another object. for example clicking a div on the page and it will toggle the image back to the original.
jQuery(function() {
var largeLink = "<a href='index.html' target='_blank' ></a>";
var largeLink2 = "<a href='#'></a>";
$(".buyimage").live('click', function() {
if ($(this).attr("class") == "buyimage") {
this.src = this.src.replace("_5.99", "_buynow");
} else {
this.src = this.src.replace("_buynow", "_5.99");
}
$(".buyimage").wrap(largeLink);
$(this).toggleClass("on")
});
});
You can use the jquery unwrap:
http://api.jquery.com/unwrap/
// for example
<script>
$("button").toggle(function(){
$("p").wrap("<div></div>");
}, function(){
$("p").unwrap();
});
</script>