Javascript/jQuery prepend images - javascript

I'm a student, and new to JS and jQuery. I'm trying to make a little facebook-like project, because I can put a lot of different things in that. Right now the HTML is just static, but as soon as i have more knowledge, I plan to make it user-generated.
I have the different 'Facebook' posts. each post is an article, and the whole is in a section titled 'newsfeed', the articles have this syntax:
<H1>, with the full name, given a class with their abbreviated name.
<p>, with their 'status update'. after this i append an <ul> with javascript, containing <li>s with like, comment and share.
I then added some jQuery/JS code to add a profile picture
profilePics = function () {
var name = $('article h1').attr('class');
name = capitalizeFirstLetter(name);
console.log(name);
var path = '../media/profile/' + name + '_Square_0.png';
console.log(path);
$('article h1').prepend('<img src="' + path + '" alt="image of ' + name + '">')
};
When I run this, it shows the alt-text of the image, indicating it can't open the image. My problem exists out of two parts:
I triple-checked the path, so basically the only thing that could be wrong with it is that i don't go to the correct parent-directory. Do i start counting position from the JS file or the directory it's in?
I want to add a different picture for each (not determined how much) post. Right now it looks at the first post for the class, and then adds it to ALL posts

To add different picture on any <h1> you have to loop over them. And your http image path must by absolute, not relative.
profilePics = function () {
var imgPath = '/http-img-path/from/web-root/';
$('article h1').each(function() {
var name = $(this).attr('class');
$(this).prepend("<img src='"+imgPath + name + "_Square_0.png' alt='image of "+name+"'");
});
};

Related

Adding Javascript Widget to a Single Tumblr Post

I only do scientific programming so I am not too familiar with javascript. I am trying to add a widget to one single tumblr post. The website I got the widget from makes it specifically for tumblr and it is:
<div class="shopthepost-widget" data-widget-id="4665345"><script type="text/javascript">!function(w,i,d,g,e,t){d.getElementById(i)||(element=d.createElement(t),element.id=i,element.src="https://widgets.rewardstyle.com"+e,d.body.appendChild(element)),w.hasOwnProperty(g)===!0&&"complete"===d.readyState&&w[g].init()}(window,"shopthepost-script",document,"__stp","/js/shopthepost.js","script")</script><div class="rs-adblock"><img src="https://assets.rewardstyle.com/production/424ab6aff12fe31b5b93d8f5ce7cc70d2953e565/images/search/350.gif" onerror='this.parentNode.innerHTML="Disable your ad blocking software to view this content."' style="width: 15px; height: 15px"><noscript>JavaScript is currently disabled in this browser. Reactivate it to view this content.</noscript></div></div>
If this is added to the actual theme on tumblr, it works great. However, I am trying to put this in just one post on tumblr. When I'm trying to make the post I will go to the html and add it in there but it will not actually show up on the site. Any tips on how to solve this? Thank you in advance.
You have two choices available to you.
First: If you can host the javascript file somewhere remotely you can link it in the bottom of the post via the editor. The beauty of this is that you can update the js without having to update your main template.
For post edits you can select settings and choose HTML markup
then add a link to the script in the bottom of the page.
Or for a page edit it is the same concept you can switch to HTML markup and add it there.
Second: you can create a function in your template and then only fire it on the relevant post or page.
The way I have done this in the past is to get the post/page name from the file path, split the file path into an array and add them to the classnames for the html element. Example here:
const dom = document.querySelector('html');
const path = document.location.pathname.split('/');
const primaryDir = path[1]; // get the primary folder
const secondaryDir = path[2]; // get secondary folder
const tertiaryDir = path[3]; // get the tertiary folder
const setIndexPage = () => {
if (!primaryDir) { // if there is no primaryDir we should assume we are on the home/index page
dom.classList.add('index');
} else if (tertiaryDir) {
dom.classList.add(primaryDir + ' ' + secondaryDir + ' ' + tertiaryDir);
} else if (secondaryDir) {
dom.classList.add(primaryDir + ' ' + secondaryDir);
} else {
dom.classList.add(primaryDir);
}
}
Now we can target our function to run only if it finds the correct selector
if (document.querySelector('.yourClassName').length) {
// run your function here
}
For .yourClassName you need to pass in the page or post name. By default Tumblr will create a unique post id (integer) and add that to the filepath. But you can also use text/verbose file names in addition.
The beauty of this method, is that the classnames will be added to every page, but you can chose to target only certain posts/pages with your js function.
Alternatively you could use this method and add the html selector only to your post/page content. So wrap your content in a div and give that a unique id or classname, but the method is the same.
Here is an example of a page where I am doing this (although I am concatenating the class names slightly differently).
I hope this makes sense.

(Jquery) Get background-image path from load[ed]() HTML element style

I'm working on my company's webpage. This is my first serious webpage and lots of doubts came at each line. Now I'm working on a News loading system, and I've one that can't solve:
I'm loading my news with jquery load, attaching elements to previously defined vars:
var newArticle = $('<div id="news-article"></div>');
var newArticleChild = newArticle.children(); //'cause i want to load articles inside #news-article, not <a></a>
var image = $('<div></div>');
var title = $("<div></div>");
var tag = $("<div></div>");
$(image).load(path + i + ".html #main-image");
$(title).load(path + i + ".html h1");
$(tag).load(path + i + ".html #tag");
$("#news").append(newArticle); //Apend articles parent to an existing page element
newArticleChild.append(image);
newArticleChild.append(title);
newArticleChild.append(tag);
HTML --------------
<div id="main-image" style="background-image: url(../../assets/images/NewsBackgroundTry.png);
"></div>
I don't really like this because it creates emty divs with another div inside, but this is not a mistake itself.
I don't really need to append image to my page, because what i want from it is it's style, that contains the path to the image in css. I'm doing this this way because I need to apply background-size: cover; style to that image.
My question is, how i can get the background-image style from image variable? I've tried lots of things and looked at as many posts as i found about it, but i can't get this value...
If the solution prevents from appending image to page, it would be much better.
Thanks everyone, Abel!
you could use var bgImg = image.css('background-image'); to get that css property and then replace the nasty url('') part to get just the image path.

How to provide different URLs for two clickable elements on the same page?

I have two clickable elements in HTML like this:
HTML
var node1 = $('' + fileName1 + '');
var node2 = $('' + fileName2 + '');
They belong to the page with url say:
http://foobar/examples.html
They have onclick listeners attached to them that retrieve some data from the server and display it on the webpage
Javascript
node1.click(function () {/*Displays table1*/})
node2.click(function () {/*Displays table2*/})
I want to change the URL for the two clicks just so that if I open the URL in a fresh tab, I get the node element clicked and the data visible. For example, conceptually, the following URL should point to the node1 clicked and data for it visible:
http://foobar/examples.html##fileName1 (does not work, but you get the idea)
I do not want to change the URL in accordance with what has been explained here as I do not want to create an HTML page for every fileName (it is an increasing list). Anchors don't help either as they just open http://foobar/examples.html and none of the nodes clicked . Neither is the answer to this question very clear to me. Can someone please help?
The first link you gave for changing the URL is what you want. However, you don't change the HTML page - you can add URL variables. For example:
http://www.example.com/mypage.html?node1=1&node2=1
Then you need to write a Javascript function at the top of your document to read the URL variables, and display the nodes that are set to 1 (or whatever value you choose) when the document has been loaded. For an example of how to read URL variables, see this answer.
You could give your nodes identifiers, like:
var node1 = $('' + fileName1 + '');
var node2 = $('' + fileName2 + '');
You would need to adjust the file names to be valid IDs.
Add the following JS:
var nodeId= window.location.hash;
$(nodeId).click();
You could then use:
http://foobar/examples.html#fileName1 (where fileName1 is adjusted as for IDs).

Jquery .html and .load

I'm trying to teach myself jQuery and I'm a little stomped with the load() method. I'm working on eBay listings. Yes, I know includes are not allowed on ebay. However, there is a workaround that has been around for a few years and ebay doesn't seem to be cracking down on it.
var ebayItemID='xxxxxxxxxxxxxx'; // This is eBay code. I cannot edit it.
<h1 id="title"> TO BE REPLACED</h1>
$(document).ready(function(){
var link = "http://www.ebay.com/itm/" + ebayItemID + "?item=" + ebayItemID + &viewitem=&vxp=mtr";
var newTitle = $('#title').load(link + "#itemTitle");
$('#title').html(newTitle);
});
What's the point of this. I want to show the item title on the description, but I want to do so dynamically,
load will not work on different domains (ebay on your case)
load will set the content directly to your element. You can't assign it to a var.
If you would like to indicate you want to extract content from a specific element you need to add a space between your link and the element id:
You can find more info on the jQuery docs
$('#title').load(link + ' #itemTitle', function() {
alert('Load was performed.');
});
When you use load will place the returned html into the element(this case #title).
So you don't need to call html after it.

need to changed markup with jquery

I have the following markup which I do not have direct access to...
<iimg src="/v/vspfiles/templates/100/images/buttons/btn_quantitydiscounts.gif" border="0" align="absmiddle">
I need to "rewrite" the above as follows...
A few things to point out is that the title is coming from a variable escape(global_Current_ProductCode) variable=productcode
The height, width, price and product id used in the second markup must be from the first markup. Note that these change depending on the product page loaded. These are not constants.
I would guess the first thing to do was to add the thickbox class. Then I am lost as to what to do next.
Basically I need to open up an thickbox iframe with the modified markup.
Register and ask again in a more parsable way.
the second part was as follows...
<aa href="/BulkDiscounts.asp?ProductID=318&ProductCode=LB30X40ES&Orig_Price=22.95&keepThis=true&TB_iframe=true&height=300&width=330"
title="LB30X40ES Laundry Bags" class="thickbox"> img border="0" align="absmiddle"
src="/v/vspfiles/templates/100/images/buttons/btn_quantitydiscounts.gif">
Untested - should get you close:
var re = /.*?\(('.*?'),.*?'(.*?)'.*(width=\d*).*(height=\d*).*/;
var match = $("a").attr("onclick").match(re);
eval("var url = " + match[1]);
$('a').unbind('click').click(function() {
TB_show(match[2], url + "&keepThis=true&TB_iframe=true&" + match[3] + "&" + match[4]);
});

Categories