I am creating a random quote generator. Every time I click the button "Get Quote", a new quote should be generated from an API, and the background color is changed. However, while the background color changes every time I click, the quote only changes the first time I click the button.
My HTML is as follows:
<body>
<div class="container-fluid">
<div id="centerThis" style="background: transparent">
<div id=target1>
<h1 class="text-center">Random Quote:</h1>
<div class="quote">
<blockquote>
<p id="quoteT">Humans are allergic to change. They love to say, 'We've always done it this way.' I try to fight that. That's why I have a clock on my wall that runs counter-clockwise.</p>
<footer id="quoteA">Grace Hopper</footer>
</blockquote>
</div>
<div class="row">
<div class="col-xs-2">
<i class="fa fa-twitter" aria-hidden="true"></i></button>
</div>
<div class="col-xs-2">
<i class="fa fa-tumblr" aria-hidden="true"></i></button>
</div>
<div class="col-xs-4">
</div>
<div class="col-xs-4">
<button id = "getQuote" class = "btn colorButton">
Get Quote
</button>
</div>
</div>
</div>
<div id="target2">
<h5 id="byAnna" class="text-center">by anna</h5>
</div>
</div>
</div>
</body>
My jQuery looks like this (I left out the code for randColor and some other un-important parts):
$(document).ready(function() {
$("#target1").css("color",randColor);
$("#target2").css("background", randColor);
$("body").css("background", randColor);
$(".colorButton").css("background", randColor);
$("#getQuote").on("click", function(){
randColor = getRandomColor();
$("#target1").css("color",randColor);
$("#target2").css("background", randColor);
$("body").css("background", randColor);
$(".colorButton").css("background", randColor);
$.ajax({url: "http://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&key=457653&format=json&lang=en", success: function(result){
$(".quote").html("<blockquote><p>" + result.quoteText + "</p><footer>" + result.quoteAuthor + "</footer></blockquote>");
}});
});
});
Thanks for any help!
It seems that you have an error on your URL:
http://crossorigin.me/http://api.forismatic...
Do you see the Ajax request on the web inspector each time you click on the button?
Regards,
Jimmy
EDIT :
The issue is the text color:
It's the same as the bg.
Try to add this line in JS:
$(".quote").css("color", "black");
Related
I have dynamically generated div's whose content contains an anchor link and path to an image.
I also have a modal box with an image tag in.
What I am trying to do is onclick of the anchor link, set the image tag path which is in the modal box.
Currently what my code does is no matter what anchor link I click, its always setting image path to the first path link.
Here is my JSFiddle link
JSFiddle
My Code:
<div id="coupon-listing-items" class="shopping-listings listings">
<div class="left-split">
<a class="ads-links" title="Test Title One" href="http://www.test.com/"><h2>Test Title One</h2></a><div class="coupon-text">(Get 20% of by staying 2 nights)</div>
<span id="sLink" class="hide">http://via.placeholder.com/350x250</span>
</div>
<div class="left-split">
<a class="ads-links" title="Test Title Two" href="http://www.test.com/"><h2>Test Title Two</h2></a><div class="coupon-text"></div>
<span id="sLink" class="hide">http://via.placeholder.com/400x350</span>
</div>
</div>
<!-- Modal Box -->
<div class="modal CouponModal">
<span class="close-modal">×</span>
<div class="modal-content">
<input type="button" class="btnprint" name="btnprint" value="Print This Coupon" onclick="PrintC('cp-image')"/>
<div id="cp-image">
<img id="coupon-image" />
<div id="caption">
<span class="vist">Visit the website: <a id="c-weblink"></a></span>
</div>
</div>
</div>
</div>
$(".ads-links").each(function(index){
$(".ads-links").on("click", function(e){
e.preventDefault(); var imgsrc = document.getElementById('sLink')
$(".CouponModal").css('display', 'block');
$("#coupon-image").attr('src',imgsrc.innerHTML);
});
$(".close-modal").click(function(e) {
$(".CouponModal").css('display', 'none');
});
});
If you click on Test title one, you will image name 350x250 displayed in the modal box, and if you close the modal box and now click on test title two, instead displaying the image 450x350 just displays the first image.
What am I missing?
Thanks and appreciate it
You are selecting the first sLink no matter which is anchor is clicked.
var imgsrc = document.getElementById('sLink');
Instead you need to base this on the sLink closest to the anchor clicked.
var imgsrc = $(this).parent().find('#sLink')[0];
//This goes up a level and finds the sLink that is in that same parent//
Note
that an ID should be unique and is likely causing part of your confusion, in this case a class might be just as useful.
your outer loop is superfluous and might cause you trouble down the road.
Updated Your Fiddle: https://jsfiddle.net/0dmc9rvt/25/
$(".ads-links").each(function(index) {
$(this).on("click", function(e) {
e.preventDefault();
debugger;
$(".CouponModal").css('display', 'block');
$("#coupon-image").attr('src', $(this).parent().find('.sLink').html());
});
$(".close-modal").click(function(e) {
$(".CouponModal").css('display', 'none');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="coupon-listing-items" class="shopping-listings listings">
<div class="left-split">
<a class="ads-links" title="Test Title One" href="http://www.test.com/">
<h2>Test Title One</h2>
</a>
<div class="coupon-text">(Get 20% of by staying 2 nights)</div>
<span class="hide sLink">http://via.placeholder.com/350x250</span>
</div>
<div class="left-split">
<a class="ads-links" title="Test Title Two" href="http://www.test.com/">
<h2>Test Title Two</h2>
</a>
<div class="coupon-text"></div>
<span class="hide sLink">http://via.placeholder.com/400x350</span>
</div>
</div>
<!-- Modal Box -->
<div class="modal CouponModal">
<span class="close-modal">×</span>
<div class="modal-content">
<input type="button" class="btnprint" name="btnprint" value="Print This Coupon" onclick="PrintC('cp-image')"/>
<div id="cp-image">
<img id="coupon-image" />
<div id="caption">
<span class="vist">Visit the website: <a id="c-weblink"></a></span>
</div>
</div>
</div>
</div>
I went back and fourth on if this is CodeReview or not, and I don't think it is.
I was messing around with CodeSchool's newest AJAX Project and it got me thinking about templating. I'm a huge abuser of
$(function() {
$.ajax({
url: 'someLink',
dataType: 'jsonp',
success: function(response) {
$.each(response.courses.completed, function(k,v){
console.log(k,v)
$('#badges').append('<div class="course"><h3>'+v.title+'</h3><img src="'+v.badge+'"><a href="'+v.url+'" class="btn btn-primary" target=_blank>See Course</a></div>')
})
}
});
});
However, I see on some pages that I inspect, they instead will assign a blank set of <div>'s etc all named 'template'
Example
<div class="templates">
<div class="deck-template">
<div class="deck-item col-xs-12 col-md-4 filter">
<div class="w3-card-4 totalDiv">
<header class="w3-container w3-blue gameTitle">
<h1 data-field="name"></h1>
</header>
<div class="w3-container imgContainer">
<p>
<img data-field="img" src="" class="gameImage" />
<p class="bodyText" data-field="game-id"></p>
</p>
<p class="imageDiv">
<div class="buttonContainer">
<span class="viewerEntry">
Want to watch someone?
<button class="w3-btn w3-dark-grey viewerWatch">Some button text</button>
</span>
</div>
</p>
</div>
<footer class="w3-container w3-blue gameFooter">
<button class="detailButton w3-blue">
<h5>Some Static Text</h5>
</button>
</footer>
</div>
</div>
</div>
</div>
This relies on heavy use of the .clone function. Is this a better method then using JS/jQ to append a ton of HTML Elements? I feel like it has to do with items being pre-loaded in the DOM rather than appended/bandwidth but I'm wondering about the logistics of 'why'.
I have 3 chat box nested in its parent and am using jquery to automatically scroll to the bottom the chat messaging area.
chatboxes
The scrolling to bottom work if the chatbox is only 1 but if its becomes two or 3 or more and I append more content to the its message area then the scroll bar will jump to the middle of the div and now it stops scrolling to the bottom as before.
$(document).on("keyup",".textareaxmsg",function(vnt){
if(vnt.keyCode === 13 ){
if($.trim($(this).val())){
var conTent = "<div class='b5d_wa msgb'><div class='d_bzAe_5'><span><span>" +$(this).val() +"</span></span></div></div>";
$(this).parents(".msg_body_a").children(".msga").append(conTent);
$(this).val("");
$(this).parents(".chat_body").children(".msg_body_a").scrollTop($(".msg_body_a")[0].scrollHeight);
}else{
$(this).val("");
}
}
});
<div class="c_boxcnt">
<div class="chat_box">
<div class="chat_header">
<div class="l_aZn_5a">
<p>James Oduro </p>
<span class="closechat "><i class="fa fa-times tooltip" title="Close"></i></span> <span class="minimizechat "></span><span class="minimizechat "><i class="fa fa-camera tooltip" title="Add Photos"></i></span>
</div>
<div class="l_aZn_5a">
<div class="cupht"><img src="uploaded/1033761452673232.jpg" /></div>
</div>
</div>
<div class="chat_body">
<div class="msg_body_a">
<div class="msga">
<div class="b5d_wa">
<div>
<div class="dz_d5ae"><img src="uploaded/1033761452673232.jpg" height="30" width="30"/></div>
<div class="d_bzAe_4">
<span class="a_r5ia"><span>made my birthday a wonderful one. God richly bless you in </span></span>
</div>
</div>
</div>
</div>
<div class="mbox">
<form method="post" action="#">
<textarea class="textareaxmsg" placeholder="Type a message..." title="Type a message"></textarea>
</form>
</div>
</div>
</div>
</div>
</div>
This worked but it is a bad code practice:
Since we can set the vertical position of the scroll area , all I did was to increase the position to uncountable number.
if( $(this).parents(".msg_body_a").children(".msga").append(conTent)){
$(this).parents(".chat_body").children(".msg_body_a").scrollTop(1000 * 1000 * 5000 *2 * 1000 *90000); /* set uncountable number */
$(this).val("");
};
I have a piece of code:
$("body").on("click", ".reply-button", function(){
alert("test");
});
That is suppose to alert me when I click on an element that is generated on the fly (it is not part of the DOM when this code is executed).
Sometimes it works just as it's suppose to. I click the button and a little alert pops up. However, other times it stop working. Nothing I bind to it will work. If I bind to the container div (also generated on the fly), it does work, but not if I change the handler to incorporate button.
I am asking for what could be the possible reasons for this error? I do not know how to go about debugging this. My first guess was that it was something due to stopImmediatePropagation or stopPropagation but I couldn't find that being used in the same area.
Does anyone have any idea on how I should go about debugging this?
EDIT:
How is the DOM being generated?
I get the HTML from a template that's hidden.
var html = $("#template").html();
Then I append the template to a div container
$("#container").append(html);
EDIT2:
Here is the template being pulled:
<div id="tweets-container" class="feed-wrapper">
</div>
<div id="tweet-template" style="display:none;">
<!-- Tweet 1 -->
<div class="tweet animated" data-scannedTweetId="s_id">
<!-- User -->
<div class="tweet-user">
<!-- User picture -->
<img class="tweet-user-picture" src="s_twt_owner_profile_img_url" />
<!-- User info -->
<div class="tweet-user-info">
<!-- User name -->
<div class="tweet-user-info-name">
s_twt_owner_name (#s_twt_owner_sn)
</div>
<!-- User biography -->
<div class="tweet-user-info-biography">
s_twt_owner_desc
</div>
</div>
</div>
<!-- User statistics (following, followers, and tweets) -->
<span class="tweet-statistics animated">
<div class="following">
<div class="statistic-count">s_twt_owner_num_following</div>
<div class="statistic-label">following</div>
</div>
<div class="followers">
<div class="statistic-count">s_twt_owner_num_follower</div>
<div class="statistic-label">followers</div>
</div>
<div class="tweets">
<div class="statistic-count">s_twt_owner_num_twt</div>
<div class="statistic-label">tweets</div>
</div>
</span>
<!-- Tweet bars/graph -->
<div class="side-information animated">
<div class="bar-wrapper">
<!-- Actual bars -->
<div class="bars">
<div class="bar big-bar bar-green" style="height: tqes_heightpx; background: tqes_color;" data-toggle="tooltip" data-placement="top" title="tq_engage_score"></div>
<div class="bar bar-yellow" style="height: tqrs_heightpx; background: tqrs_color;" data-toggle="tooltip" data-placement="top" title="tq_relevancy_score"></div>
<div class="bar bar-light-green" style="height: sks_heightpx; background: sks_color;" data-toggle="tooltip" data-placement="top" title="s_klout_score"></div>
<div class="bar bar-green" style="height: sls_heightpx; background: sls_color;" data-toggle="tooltip" data-placement="top" title="s_legitimacy_score"></div>
<div class="bar bar-gray" style="height: tqgs_heightpx; background: tqgs_color;" data-toggle="tooltip" data-placement="top" title="tq_geography_score"></div>
</div>
<!-- Labels that correspond with each bar -->
<div class="bar-labels">
<div class="bar-label big-bar-label" data-toggle="tooltip" data-placement="bottom" title="Score">tq_engage_score</div>
<div class="bar-label-icon" style="font-size: 12px; color: #000;" data-toggle="tooltip" data-placement="bottom" title="Relevancy">
<i class="fa fa-bullseye"></i>
</div>
<div class="bar-label-icon" data-toggle="tooltip" data-placement="bottom" title="Influence">
<i class="fa fa-users"></i>
</div>
<div class="bar-label-icon" data-toggle="tooltip" data-placement="bottom" title="Legitimacy">
<i class="fa fa-check-circle"></i>
</div>
<div class="bar-label-icon" data-toggle="tooltip" data-placement="bottom" title="Geography">
<i class="fa fa-map-marker"></i>
</div>
</div>
</div>
<!-- Notes below the bars/graph -->
<div class="explanations">
<!-- Note below the bars/graph -->
<div class="explanation">
<div class="explanation-check"><i class="fa fa-first-comment"> </i>
<div class="explanation-text">
comment_one
</div>
</div>
</div>
<!-- Note below the bars/graph -->
<div class="explanation">
<div class="explanation-check"><i class="fa fa-second-comment"> </i>
<div class="explanation-text">
comment_two
</div>
</div>
</div>
</div>
</div>
<!-- Tweet score -->
<div class="score-wrapper">
<div class="score animated">tq_engage_score</div>
</div>
<!-- Tweet content -->
<div class="tweet-content">
s_twt_text
</div>
<!-- Time since tweet was posted -->
<div class="tweet-time-elapsed">
s_twt_time
</div>
<!-- Area below tweet with reply textarea and buttons -->
<div class="tweet-reply-section animated">
<!-- Reply textarea -->
<textarea class="tweet-reply animated">#s_twt_owner_sn </textarea>
<!-- Buttons -->
<div class="buttons animated">
<!-- Small buttons on top of reply button -->
<div class="top-buttons">
<span class="character-count">
</span>
</div>
<!-- Reply button -->
<div class="reply-button">
Reply <i class="fa fa-reply"></i>
</div>
</div>
</div>
</div>
</div>
JavaScript:
/**
* Add a tweet to the feed.
*/
function _addTweetToFeed(tweet, keywords) {
/** Get the tweet template */
var tweetHtml = $('#tweet-template').html();
// add score heights and colors properties to the tweet
tweet = _setScoreBars(tweet);
/** Linkify elements of the tweet */
tweet.s_twt_text = twitterify(tweet.s_twt_text); // the tweet
tweet.s_twt_owner_desc = twitterify(tweet.s_twt_owner_desc);
// fix search terms to be highlighted
tweet.s_twt_text = _highlightSearchTerms(tweet.s_twt_text, keywords); // the tweet
tweet.s_twt_owner_desc = _highlightSearchTerms(tweet.s_twt_owner_desc, keywords);
// change from twitter links to readable links
tweet = _fixTweetLinks(tweet);
/** Make numbers readable */
tweet.s_twt_owner_num_following = abbrNum(tweet.s_twt_owner_num_following, 1);
tweet.s_twt_owner_num_follower = abbrNum(tweet.s_twt_owner_num_follower, 1);
tweet.s_twt_owner_num_twt = abbrNum(tweet.s_twt_owner_num_twt, 1);
/** Loop through the properties of tweet object and populate tweetHtml with them */
for (var prop in tweet) {
if (tweet.hasOwnProperty(prop)) {
tweetHtml = _replaceAll(tweetHtml, prop, tweet[prop]);
}
// add comments
tweetHtml = _addComments(tweet, tweetHtml);
/** If both location and url are not present, remove the comma */
if (!(tweet.s_twt_owner_loc && tweet.s_twt_owner_url)) {
$('#url_comma').html('');
}
}
$('#tweets-container').append(tweetHtml);
}
"Sometimes it works just as it's suppose to" this line alone suggests that you run your code prior to DOM creation. sometimes your browser creates the dom fast enough and the handler is being attached to the body, and sometimes your javascript runs first and it isnt being attached. wrap your code in this:
$(function(){
$("body").on("click", ".reply-button", function(){
alert("test");
});
});
Does anyone have any idea on how I should go about debugging this?
Sometimes it's best to pull out a tiny portion of code, and see if it works in isolation. For example: http://jsfiddle.net/6v7z9fak/
js:
$("body").on("click", ".reply-button", function(){
alert("test");
});
html:
<button type="button" class="reply-button">Reply</button>
As you'll see, it works fine. So you can be confident that the error is not in that bit of code alone. It is either another part of the code, or how the parts are interacting together, or something else. Now slowly add more code, test, and see where it breaks.
Hi i have this problem: I want to click on div which will flipped (this is work) but next step is flipp div back on click on "x" (this is my problem).
HTML code:
<div class="col-md-4">
<div class="balik">
<div class="panel panel-default panel-cube">
<div class=" flip">
<div class="card">
<div class="panel-body face front">
<h4>Balík 28 dní</h4>
<br>
<h1>16,80€</h1>
<br>
<h4>Zisti viac o balíku »</h4>
</div>
<div class="panel-body face back">
<p class="close">x</p> <h4>O Balíku 28 dní</h4>
» celkom 28 dní na topovanie
<br />» 5 topovaných inzerátov
<br />» -30% z ceny oproti balíku 7 dní
<br />
<br>
<button class="btn btn-success"><i class="fa fa-shopping-cart"></i> Kúpiť</button>
</div>
</div>
</div>
</div>
</div>
</div>
JQUERY code:
$(function(){
$('.flip').click(function(){
$(this).find('.card').addClass('flipped')
});// this is work
$('.close').click(function(){
$('.flip').find('.card.flipped').removeClass('flipped')
}); // this is not work
});
Thanks for answers.
Because .flipped is essentially a dynamically-created element, you'd need to use event delegation:
http://jsfiddle.net/isherwood/7Zg92/
$(document).on('click', '.close', function () {
$('.flip').find('.card.flipped').removeClass('flipped')
});
That's because events bubble up, you should stop the propagation of the event:
$('.close').click(function(event) {
event.stopPropagation();
$('.flip').find('.card.flipped').removeClass('flipped');
});
http://jsfiddle.net/aaLUs/