i want to understand this piece of code as i m a beginner.Mostly these red color fonts. they are taking which page value?
$(function() {
$("#title").blur(function() { QuestionSuggestions(); });
});
function QuestionSuggestions() {
var s = $("#title").val();
if (s.length > 2 && !($("#title").hasClass('edit-field-overlayed'))) {
document.title = s + " - Stack Overflow";
$("#question-suggestions").load("/search/titles?like=" + escape(s));
}
}
function QuestionSuggestions() {
var s = $("#title").val(); // Here we take the value of element with ID "title"
// If the length of the title is bigger than 2 or
// the element doesn't have 'edit-field-overlayed' class
if (s.length > 2 && !($("#title").hasClass('edit-field-overlayed'))) {
// we set the title of the document as <title>[our old title] - Stack Overflow</title>
document.title = s + " - Stack Overflow";
// Load data from the server and place the returned HTML into the matched element.
$("#question-suggestions").load("/search/titles?like=" + escape(s));
}
}
If you element with id title has longer title than 2, lets say "My title" and there is no class "edit-field-overlayed" we change the page title to "My title - Stack Overflow" and load html/text in element "#question-suggestions" by querying the URL http://yoursite.tld/search/titles?like=My%20title
This looks like jQuery code. The expression $("#title") is a call to the jQuery $ function. It looks for the HTML tag with id="title" and wraps a utility object around it. .blur is a method of that utility object, which supplies a function to be called when the mouse moves off the corresponding element.
The best thing would be to get stuck into a jQuery tutorial like this one.
The peice of code posted, condensed to a sentence is
"When the field with id 'title' blurs, execute an ajax query passing the content of that field as a parameter"
Related
EDIT: This is a more sound approach, since provided answer may have bugs when implementing a tags, or img tags.
================================================================
I am calling blog data from an API. (I've reformatted the data into an array by month).
So far, the blog titles print to the web page. I'd like a user to be able to click a title and have its description revealed.
Here is some of my code so far:
var blogPosts = $('#blog-posts');
$.each(byMonth, function(key, value) {
var outer = byMonth[key]
$.each(outer, function(k, v) {
var inner = outer[k]
var monthBlogPosts = $('<div class = "month"> </div>').appendTo(blogPosts);
$.each(inner, function(i, obj) {
title = inner[i].Title
description = inner[i].Description
date = inner[i].DatePublished
$('<div class = "title-list"><h3 class = "unique-title">' + title + '</h3></div>').appendTo(monthBlogPosts)
// if a title is clicked, show its Description
showDescription(description);
})
})
});
function showDescription(d){
$('.unique-title').on('click', function(){
$('<p>' + d + '</p>').appendTo('body')
console.log(d)
})
}
When I click a title, all descriptions print instead of the matching description. I understand this is because I called the function in a nested loop, but I've also had trouble calling the description variable outside of it.
I have also tried
showDescription(title, description)
//...
function showDescription(t, d){
$(title).on('click', function(){
$('<p>' + d + '</p>').appendTo('body')
console.log(d)
})
}
but then nothing is printed to the html page.
Essentially, I'd like to grab the title index, and print it's respective description when its clicked.
you should use event delegation to attach a click event to the document that will bubble up and trigger when .title-list is the event target.
$(document).on('click', '.title-list', function(event) {
showDescription(event.currentTarget) // pass the element being clicked (we will need it later)
})
you would also need to modify the way you get the description.
you could store you description in a data attribute of .title-list like so:
$('<div class = "title-list" data-description="'+ description +'"><h3 class = "unique-title">' + title + '</h3></div>').appendTo(monthBlogPosts)
so you can now modify showDescription() so it would get the data from the element we pass to the function
function showDescription(element){
var d = $(element).data('description')
$('<p>' + d + '</p>').appendTo('body')
console.log(d)
})
So ok. From whatever I could understand (by looking at your code). You cannot register an event with simple on for dynamically added element. You have to use on delegate.
Try this
1) remove the function call (inside a loop)
2) delete the entire function showDescription and add event as below:
$('#blog-posts').on('click', '.unique-title',function(){
alert('title clicked').
});
3) As to display the description I think the best way will be to add the description in a div and hide it. Display it later once the title is clicked.
(inside the loop)
$('<div class = "desc" style="display:none">' + description + '</div>').appendTo(monthBlogPosts);
then on #2 above. Replace with this.
$('#blog-posts').on('click', '.unique-title',function(){
$(this).next('.desc').show(); //I am assuming desc will be next to the clicked title here. You can modify it as needed.
});
Finally, this is just an overview of a code so might not work as expected but I am pretty sure this should give you an idea and get you started
i'm no js expert but need to execute some js in my applescript. Don't know if this is possible as the html page contains several instances of this div class.
If nested div class ".product_card__title" contains "my search term"
Extract href link from nested class ".js-search-product-link"
From main div with the class ".product_card"
A ANLTERNATIVE VERSION TO THE ONE ACCEPTED HERE IN THIS THREAD.
My Html:
<div class="product_card powersearch__product_card">
<a href="/shop/XYZ" class="js-search-product-link">
<div class="product_card__image" style="background-image:url(https://image.jpg);"></div>
<div class="product_card__title">SEARCH FOR THIS TITLE</div>
<div class="product_card__meta">€14</div></a></div>
What i have so far is:
tell application "Safari"
open location "https://teespring.com/search?q=rocker"
delay 5
set theLinks to (do JavaScript "Array.prototype.slice.call(document.querySelectorAll('.product_card')).map(function(d,i){var title = d.querySelector('.product_card__title'),link = d.querySelector('a');if(title && link && /Rocker/gi.test(title.textContent)){return link.href}})")
end tell
return theLinks
Replace yourSearchTerm with whatever you want to search below:
Array.prototype.slice.call(document.querySelectorAll(".product_card"))
.map(function(d,i){
var title = d.querySelector(".product_card__title"),
link = d.querySelector("a");
if(title && link && /yourSerchTerm/gi.test(title.textContent)){
return link.href
}
})
For all your divs with class of "product_card" it will return an array containing the hrefs, for the ones it could find, otherwise undefined
FIDDLE:
https://jsfiddle.net/ibowankenobi/gc6r2h3v/1/
As apple returns the last global value it might help to change the part where you set the theLinks variable:
set theLinks to (do JavaScript "someGlobal = Array.prototype.slice.call(document.querySelectorAll('.product_card')).map(function(d,i){var title = d.querySelector('.product_card__title'),link = d.querySelector('a');if(title && link && /Rocker/gi.test(title.textContent)){return link.href}})")
I´m trying to mix a string to assign variable(array) I don´t know what´s wrong I can not get it work.
in php I will send array of id to javascript via json_encode();
I will get like :key= 1, 2, 3 etc.
Here is aline of those div:
text
Then in javascript with a conditon like this:
$("#swas"+key).removeClass('colorme');
function xx(key, arr) {
for (var v in arr) { //LOOP
var k = arr[v];
if ($("#swas" + k) != key) {
$("#swas" + k).addClass('colorme');
}
}
}
What have I done wrong ?
UPDATE
The reason I want to mix "swas" with array because in php page there´re alot of div that name
swas1, swas2, swas3, swas4.........>etc
And "key" is the id of current div that will be clicked. and "key" value : 001, 002, 003, 004 etc
What I want to do is to make the other div (that´s not the current div )to not change color.
that´s why I have to mix the word "swas" with the "key" in javascript.
UPDATE2
Now It work with script above but new probelm, it not remove the class when clicked :S
UPDATE3
Now everything just work fine after I move the $("#swas"+key).removeClass('colorme');
To the bottom :) S
You mention swas1 swas2 etc, but then you mention arr being 001 002 etc. These will not match.
It would be so much easier if you used jquery
$('#swas' + k).addClass('colorme');
You can use something like Firebug to ensure that your selection is correct.
If you want to use javascript then test to see if the Div already has a class before appending
var el = document.getElementById('hello');
if(el) {
el.className += el.className ? ' someClass' : 'someClass';
}
How can I locate the tag which calls a JQuery script, when
the tag is dynamically loaded, so won't be the last
tag on the page?
I'm using the MagicSuggest autosuggest library. I want to give certain suggested items a different background color depending on their contents, which I'm currently doing by adding JQuery inside a tag, which I'm adding on to the String which is returned to be rendered inside the selection div. Then, to get the div the item is suggested in, I need to essentially get the parent() of the tag, and change it's css() properties. How can I get this current script tag however?
I'm currently assigned each new tag an id generated from incrementing a JS variable - which works, but isn't very 'nice'! Is there anyway I can directly target the tag with JQuery?
If it perhaps makes it clearer, here is my current selectionRenderer function.
selectionRenderer: function(a){
var toRet = a.english;
var blueBgScript = "<script id=ft" + freeTextFieldID + ">$('#ft" + freeTextFieldID + "').parent().css('background', 'blue');</script>"
if(a.id==a.english){
toRet += blueBgScript;
freeTextFieldID++;
}
return toRet;
},
Why don't you add some code at afterrender event instead? Add some tag to flag the options that need a different background, then detect the parents and add a class (or edit the bg property) or whatever you like:
var newMS = $('#idStr').magicSuggest({
data: 'states.php',
displayField: 'english',
valueField: 'id',
selectionRenderer: function(a){
var toRet = a.english;
if(a.id==a.english) toRet = "<span class='freetext'>" + toRet + "</span>";
return toRet;
},
});
$(newMS).on('selectionchange', function(event,combo,selection){
var selDivs = $(event.target._valueContainer[0].parentNode).children('div'); //Get all the divs in the selction
$.each(selDivs,function(index,value){ //For each selected item
var span = $(value).children('.freetext'); //It if contains a span of class freetext
if(span.length == 1) $(value).css('background','blue'); //Turn the background blue
});
Sorry for asking, but i am really newbie in jquery.
$(".productTopMenu").click(function() {
$("#breadcrumbs").html("Home / <strong>Product</strong>");
});
$(".downloadTopMenu").click(function() {
$("#breadcrumbs").html("Home / <strong>Download</strong>");
});
this is a breadcrumbs. every .productTopMenu clicked, #breadcrumbs will call the text.
if there is 15 pages, i must put 13 more copies of that script.
how to shorten that script like :
.productTopMenu = Home / <strong>Product</strong>
.downloadTopMenu = "Home / <strong>Download</strong>
the text always called inside #breadcrumbs.
is there a way to shorten this script ?
thanks in advance
any suggestion are welcome.
Something like:
$('[class$="TopMenu"]').click(function() {
$("#breadcrumbs").html("Home / <strong>" + getNameFromClass(this.className)
+ "</strong>");
});
function getNameFromClass(theClass) {
// take substring and make title case here
}
I haven't tested it but this should work:
// your data as an array containing objects
var item = [
{
"selector" : ".productTopMenu",
"label" : "Product"
},
{
"selector" : ".downloadTopMenu",
"label" : "Download"
}
],
i = item.length - 1,
$breadcrumbs = $('#breadcrumbs'); // Dom Cache
while (i >= 0) {
(function (i) {
$(item[i].selector).click(function () {
$breadcrumbs.html('Home / <strong>' + item[i].label + '</strong>');
});
}(i));
}
As everyone else has suggested, take the name from an existing element, and then use common class to hook up the click delegate.
If you haven't got the text as it should appear, you could try outputting it as a data-* attribute...
<a href="#" data-title="Downloads" />Go to Downloads</a>
That way you can control the name separately from everything else, at least.
You can give each of this menu elements the same calls, a unique ID and have a mapping id -> text:
var paths = {
'productTopMenu': "Home / <strong>Product</strong>",
'downloadTopMenu': "Home / <strong>Download</strong>"
};
$('.menuItem').click(function() {
if(paths[this.id]) {
$("#breadcrumbs").html(paths[this.id])
}
});
DEMO
You could also use a data- attribute to store some identifier, it does not have to be the id attribute.
Of course there are other ways. You have to decide how automatic or flexible you want the solution to be.
Try to use .each()