How to stop jQuery page elements from repeating? - javascript

My jQuery code runs when I click a link. However, if I click the link multiple times, the code will repeat itself and appear under the previous code, which I don't want it to do.
Also, if I click the "close" option, and reopen it, it will have repeated. How do I stop it from doing this? Here is the code, by the way:
$("#pop").click(function() {
$("#overlay_form").fadeIn(1000);
$("#statsStr").append('<br />' + strOne).fadeIn(1000);
$("#statsCun").append('<br />' + cunOne).fadeIn(1000);
$("#statsAgil").append('<br />' + agilOne).fadeIn(1000);
$("#statsWis").append('<br />' + wisOne).fadeIn(1000);
});
$("#close").click(function(){
$("#overlay_form").fadeOut("slow");
$("#statsStr").fadeOut("slow");
$("#statsCun").fadeOut("slow");
$("#statsAgil").fadeOut("slow");
$("#statsWis").fadeOut("slow");
});
Thanks for the help!
EDIT: I have taken the suggestion to change my code to this:
// append the strings only once on load
$(function() {
$("#statsStr").append('<br />' + strOne);
$("#statsCun").append('<br />' + cunOne);
$("#statsAgil").append('<br />' + agilOne);
$("#statsWis").append('<br />' + wisOne);
});
$("#pop").click(function() {
$("#overlay_form, #statsStr, #statsCun, #statsAgil, #statsWis").fadeIn(1000);
});
$("#close").click(function(){
$("#overlay_form, #statsStr, #statsCun, #statsAgil, #statsWis").fadeOut("slow");
});
And while it works great, there is one problem. The game I am making requires the "#pop" function to update every once in a while to display what your "stats" are. Is there any way to refresh the code so that it will display the updated variables?

EDIT try this for your solution:
//call this method whenever you want to update your stats
//passing in the variables
var updateStats = function(str, cun, agil, wis) {
$("#statsStr").html('<br />' + str);
$("#statsCun").html('<br />' + cun);
$("#statsAgil").html('<br />' + agil);
$("#statsWis").html('<br />' + wis);
};
$("#pop").click(function() {
$("#overlay_form, #statsStr, #statsCun, #statsAgil, #statsWis").fadeIn(1000);
});
$("#close").click(function(){
$("#overlay_form, #statsStr, #statsCun, #statsAgil, #statsWis").fadeOut("slow");
});
$(document).ready(function() {
// assuming you have set these variables in the current scope.
updateStats(strOne, cunOne, agilOne, wisOne);
});

Consider using one() instead, which only triggers the event once.

It sounds like what you really want to do is show the #overlay_form on pop and hide it on close.
You could add the html to the page when it is rendered but use display none. That way you can simply show / hide when you click pop or close.
See if this example has the behavior you would like.
http://jsfiddle.net/qh4eN/1/
<style>
#overlay_form {
display: none;
}
</style>
<div>
<span id="pop">pop</span>
<span id="close">close</span>
<div id="overlay_form">
<div id="statsStr">statsStr</div>
<div id="statsCun">statsCun</div>
<div id="statsAgil">statsAgil</div>
<div id="statsWis">statsWis</div>
</div>
</div>
<script>
var strOne = "strength";
var cunOne = "constitution";
var agilOne = "agility";
var wisOne = "wisdom";
$("#pop").click(function() {
$("#statsStr").text(strOne);
$("#statsCun").text(cunOne);
$("#statsAgil").text(agilOne);
$("#statsWis").text(wisOne);
$("#overlay_form").fadeIn(1000);
});
$("#close").click(function(){
$("#overlay_form").fadeOut("slow");
});
</script>

Related

I want to get the text content of an element inside $(this) on jQuery

function newFunc(){
excuseDivs = " "
excuseArrayItem = excuse + " : " + "<span class='excuseDivTime'>" + endTime + "</span>";
excuseArray.unshift(excuseArrayItem)
excuseArray.forEach(function(excuse){
excuseDivs +="<div class='excuse-div'>"+excuse+"</div>"
})
I want to add a click listener to the div that this function creates. I want that click listener to get the text content of the span inside the div (class of excuseDivTime). Is there some way to get something like ($(this) > span).textContent ??
You can do this fairly easy in either plain JavaScript or stick with jQuery.
You need to query for the span under the clicked div.
If you are using jQuery, stick with jQuery method calls e.g. .text() instead of .textContent.
// Plain JavaScript
document.getElementById('MyDiv').addEventListener('click', function(e) {
alert(e.currentTarget.querySelector('span').textContent);
});
// jQuery Version
$('#MyDiv').on('click', function(e) {
alert($(this).find('span').text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="MyDiv">Click me! <span>This text will show in an alert.</span></div>
Use find() or children()
$(document).on('click', '.excuse-div', function() {
console.log( $(this).find('.excuseDivTime').text() );
});

Jquery tool tip is not showing with AJAX data load

I am having issue regarding the showing tooltip on the ajax loaded content, I am adding the tooltip to ul with a function, and trying to bind it with mouse over event as it works.
str += '<li><a href="#" class="tooltip-1" data-placement="top" data-original-title="' + _icon_list[2] + ':' + obj[_icon_list[1]] + '">' +
'<i class="' + _icon_list[0] + '"></i></a></li>';
after adding the data I am trying to bind it
$('a.tooltip-1').on({
"mouseover": function() {
tool_tip();
},
"mouseout": function() {
$(this).tooltip("disable");
}
});
function tool_tip() {
$('[data-toggle="tooltip"]').tooltip()
}
it's getting callback but not showing the tooltip? here is the link of theme which has the tooltip and i am using it with my dynamic content.
http://www.soaptheme.net/wordpress/citytours/shortcodes/
Where is your ajax function?
Just add a title="your tooltip text here" in your href and in you ajax callback call this command.
$('a.tooltip-1').tooltip( );

How to retrieve id from selected item using "this"

I am new at jQuery/javascript. I tried some suggestions I found on this forum but so far it did not help.
THis is what I am trying:
When loading categories from a database ( using ajax) this HTML statement is added for each category:
$("#Links ul").append('<li id=\"cat' + i + '" data-catid=' + i + '>' + categorie_tekst[1] + '</li>');
Using F12 I see that the lines are correctly added.
E.g. <li id="cat3" data-catid="3">Seafood </li>
Next step is selecting a category in the screen and retrieve the products of this category using the value set for data-catid.
I have been told that I could "this.id" but so far no luck. Displaying the value of this.id with alert returns the correct value but for some reason I can't use it.
When I add (#cat3).attr(“data-catid”) in the code it works. But different options like these did not work:
("#cat"+ this.id).attr(“data-catid”)
(this).attr(“data-catid”)
var x = $(this).id();
var rest = x.substr(4, 1);
Everything with "this" creates error : Uncaught TypeError: ("#cat" + this.id).attr is not a function...
Trying to display any of these options does not give any output (not even a popup when I set an alert)
Any help would be appreciated!
You are loading dynamic values. Please use Event Delegation. And the $.one() binds the event once.
You need to add this in your ready function.
$(document).ready(function () {
$("#Links ul").one("click", ".cat", function(){
alert($(this).data('catid'))
});
});
To get the IDs of the elements, use $(this).attr("id") or $(this).prop("id") (latest jQuery) instead of this.id, as sometimes, it might return the jQuery object.
As you are creating elements like
$("#Links ul").append('<li class="cat" id=\"cat' + i + '" data-catid=' + i + '>' + categorie_tekst[1] + '</li>');
create elements using jQuery
$("#Links ul").append( $('<li></li>', {
class: "cat",
id: "cat" + i,
data-catid: i,
text: categorie_tekst[1]
});
As you are creating elements dynamically use Event Delegation. You have to use .on() using delegated-events approach.
$(document).ready(function () {
$("#Links ul").on(event, ".cat", function(){
alert($(this).data('catid'))
});
});

Javascript mouse over on dynamic amount of elements

My goal is on hover a p element contained inside an a tag gets bigger on hover. I have achieved this via css3 transitions, however this is not the issue.
A loop creates a variable amount of elements in the form below on each iteration.
anchorElement = "<a id='anchor" + countWide + "' class=\"boxOPT oneplustwo\" alt=\'"+ image_website +"' style=\"cursor:pointer;width:"+ itemWidth + "px"+";height:"+anchorHeight+";position:absolute;left:"+ locationLeft + "px"+";top:0.3%;\" ><p id=\"test\" class=\"popupDynamic\"> " + popupImageTitles[i] + "</p>";
anchorElement += '</a>';
I would love to be able to add a mouse in/out effect whenever the user scrolls on the relevant anchor. each p tag contains unique information that needs to be conveyed and on hover only the relevant one should react.
I dont want to it it the below way, making two each of the methods every time a new element is created above. is there a way to have the following below which will work for a dynamic amount of elements?
$("#anchor" + etc).mouseover(function() {
document.getElementById("test").style.height="1.1em";
});
$("#anchor" + etc).mouseout(function() {
document.getElementById("test").style.height="1.1em";
});
My version of suggestions. the console logs works.
.popupHighlight {
color: red;
}
..
$('.boxOPToneplustwo').mouseover(function (e) {
console.log("in");
$(e.target).next('p').addClass("popupHighlight");
});
$('.boxOPToneplustwo').mouseout(function (e) {
$(e.target).next('p').removeClass("popupHighlight");
});
What about selecting all a elements?
$('a').mouseout(function() {
//do stuff in here
});
or better yet, have a class selector:
$('.mySpecialRolloverClass').mouseover(function (e) {
$(e.target).next('p').addClass("highlight");
});
$('.mySpecialRolloverClass').mouseout(function (e) {
$(e.target).next('p').removeClass("highlight");
});
which would go hand in hand with
An anchor
and
.highlight {
color:red;
}
Here's a jsfiddle demo:
http://jsfiddle.net/8J6kM/
The #yochannah answer is correct, however if you want to add more links dynamically, you then need to use on method instead of mouseover and mouseout, otherwise it won't work. See the demo and jQuery documentation for further details.
// I assumed that links are placed inside of a container element: #links
$('#links').on('mouseover', '.mySpecialRolloverClass', function (e) {
$(e.target).next('p').addClass("highlight");
});

JQuery: How do you change a graphic on a mouse hover event?

Using JQuery, how do I change a map icon whenever I mouse hover over a row in an HTML table/div?
Here is an example:
http://www.sfsunriseidx.com/homes/94131/?uuid=9ed7269b-5327-4c88-ba15-f700ed343d69&source=REDIR
Notice when you mouse hover over a home listing on the left, the corresponding map icon on the right changes.
Question: how do I emulate this functionality using JQuery?
Update: It was suggested below that an ID linked the two elements. If that is the case, how would you still accomplish this?
Use the for="" attribute in html, like
Hover Link
On the image:
<img id="mapIcon4" src="myImg.png" />
jQuery, using the hover function to animate the corresponding ID, the same one in the for:
$(".mapHover").hover(function() {
$("#" + $(this).attr('for')).animate({"left": "-=50px"}, "slow");
}, function() {
$("#" + $(this).attr('for')).animate({"right": "+=50px"}, "slow");
});
Probably both elements are linked by a ID..
Something like this:
$(document).ready(function() {
var googleMap = $("#googleMaps");
$('a', '#mapLinks').hover(function() {
var index = $(this).index(this);
$('img:eq(' + index + ')', googleMap).animate({
width: '+=10%'
});
}, function() {
var index = $(this).index(this);
$('img:eq(' + index + ')', googleMap).animate({
width: '-=10%'
});
});
});
Just make sure you change the "#googleMaps" and "#mapLinks" thing :)

Categories

Resources