How to add links to images within HTML dynamically with JS? - javascript

I have 50 divs like the below, and the image is not clickable. I would like to make the image clickable, depending on what link the div contains: it is always the href link in the article_title tag.
How can I achieve this with adding just a few lines of JavaScript?
I was thinking of adding an ID to each img tag manually, and then use getElementById and do some magic, but that would take too long.
<div class="col-md-4 article">
<img src="7tips.jpg" alt="Canary Wharf" title="7 Tips For Lasting In Your Career" width="324" height="235">
<div class="article_category">
<a href=”http://www.canarywharfian.co.uk/forums/wealth-management/”>Wealth Management</a>
</div>
<div class="article_meta">
<h1 class="article_title">7 Tips For Lasting In Your Career</h1>
<div class="col-md-6 author_date">SmallCapPM - <span class="date"> Mar 10, 2016</span></div>
<div class="article_abstract">
Many of you are hoping and planning for a long and successful career in finance...
</div>
</div>
</div>

Maybe this (using jQuery):
<script>
$(document).ready(function () {
$('.block').each(function( index, value ) {
let href = $(this).find('a[href]').attr('href');
$(this).find('img').wrap('<a href=' + href + '></a>');
});
});
</script>

if you use jQuery, you can simply wrapping the images with element.
$(function(){
// traversing all the images
$('img').each(function(){
// get the link by finding from parent
var link = $(this).parent().find('.article_title a').attr('href');
// replace the image with link + image
$(this).replaceWith('' + $(this)[0].outerHTML + '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="col-md-4 article">
<img src="http://www.canarywharfian.co.uk/7tips.jpg" alt="Canary Wharf" title="7 Tips For Lasting In Your Career" width="324" height="235">
<div class="article_category">
Wealth Management
</div>
<div class="article_meta">
<h1 class="article_title">7 Tips For Lasting In Your Career</h1>
<div class="col-md-6 author_date">SmallCapPM - <span class="date"> Mar 10, 2016</span></div>
<div class="article_abstract">
Many of you are hoping and planning for a long and successful career in finance...
</div>
</div>
</div>

Per your tag of vanila Javascript, what you can do is to search for and cache all your articles. Within each article search for anchor inside your title and set its href to a newly created anchor. Append the image into the newly created anchor and prepend it into your article.
A simple example (H1 font-size reduced for demo):
var articles = document.getElementsByClassName('article');
[].forEach.call(articles, function(article) {
var image = article.querySelector('img:first-child');
var title = article.querySelector('h1.article_title > a');
var anchor = document.createElement('a');
anchor.href = title.href;
anchor.appendChild(image);
article.insertBefore(anchor, article.firstChild);
});
h1 { font-size: 12px; }
<div class="col-md-4 article">
<img src="//placehold.it/120x64" alt="Canary Wharf" title="7 Tips For Lasting In Your Career">
<div class="article_category">
Wealth Management
</div>
<div class="article_meta">
<h1 class="article_title">7 Tips For Lasting In Your Career</h1>
<div class="col-md-6 author_date">SmallCapPM - <span class="date"> Mar 10, 2016</span></div>
<div class="article_abstract">
Many of you are hoping and planning for a long and successful career in finance...
</div>
</div>
</div>
<hr/>
<div class="col-md-4 article">
<img src="//placehold.it/120x64" alt="Canary Wharf" title="7 Tips For Lasting In Your Career">
<div class="article_category">
Wealth Management
</div>
<div class="article_meta">
<h1 class="article_title">7 Tips For Lasting In Your Career</h1>
<div class="col-md-6 author_date">SmallCapPM - <span class="date"> Mar 10, 2016</span></div>
<div class="article_abstract">
Many of you are hoping and planning for a long and successful career in finance...
</div>
</div>
</div>
Notice, how the links to bing and google are picked up from the title anchors and inserted into a new anchor wrapping the images.

Related

Add a Like + Sort Function to existing dynamic funcion

I wrote a function that dynamically creates a webpage for me based on a json database.
Now I want to add 2 functions:
If you click the like img (its got the id button) the like counter should increase on the webpage by 1. Pretty easy just a on(click) with jQuery variable++ and then .text(variable)
A sort function - based on the likes one item received, you should be able to sort it (most liked div first, 2nd, 3rd....
I can write it for each individually with individual variables when I give all the like buttons and outputs a separate id but I wanted to make it dynamic so if you add new data to json file it dynamically works with the like and sort function.
The likes are not saved anywhere for now.
Since sitting on it for 3h and google so much and so much stackoverflow I think I overloaded my brain with different stuff and now nothing seems to work ^^
function filmInsert(insert) {
$.each(film, function(i, data) { //.each statt loop
let box =
`<div class="boxwrapper">
<div class="imgbox">
<img src="${data.img}" alt="${data.titel}">
</div>
<div class="textbox">
<h3>${data.titel}</h3>
<p>${data.beschreibung}</p>
<p> <a id="button${data.id}">
<img src="img/budspencer_official.png"> Like
</a>
<span class="output${data.id}">${data.likes}</span>
</p>
</div>
</div>`;
insert.append(box);
});
}
I've added a container element for the boxwrapper items as I assume you have one and as it's better to have one instead of just adding the sorted items to the body of the HTML document.
$(document).on("click", ".textbox a", function() {
let likes = parseInt($(this).closest(".textbox").find("span").text());
$(this).closest(".textbox").find("span").text(likes + 1);
});
$("#sort").on("click", function() {
let divs = $(".boxwrapper")
let sorted = divs.sort(function(a, b) {
return $(a).find("span").text() < $(b).find("span").text() ? 1 : -1;
});
$(".container").html(sorted);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="boxwrapper">
<div class="imgbox">
<img src="example.gif" alt="Title">
</div>
<div class="textbox">
<h3>Titel</h3>
<p>Description</p>
<p> <a id="button1">
<img src="https://dummyimage.com/40x40/000/fff&text=1"> Like
</a>
<span class="output1">0</span>
</p>
</div>
</div>
<div class="boxwrapper">
<div class="imgbox">
<img src="example.gif" alt="Title">
</div>
<div class="textbox">
<h3>Titel 2</h3>
<p>Description 2</p>
<p> <a id="button2">
<img src="https://dummyimage.com/40x40/000/fff&text=2"> Like
</a>
<span class="output2">0</span>
</p>
</div>
</div>
</div>
<button id="sort">
Sort
</button>

Link simillary name classes so that when one is clicked the other is given a class

Basically, I'm asking for a way to optimize this code. I'd like to cut it down to a few lines because it does the same thing for every click bind.
$("#arch-of-triumph-button").click(function(){
$("#arch-of-triumph-info").addClass("active-info")
});
$("#romanian-athenaeum-button").click(function(){
$("#romanian-athenaeum-info").addClass("active-info")
});
$("#palace-of-parliament-button").click(function(){
$("#palace-of-parliament-info").addClass("active-info")
});
Is there a way to maybe store "arch-of-triumph", "romanian-athenaeum", "palace-of-parliament" into an array and pull them out into a click bind? I'm thinking some concatenation maybe?
$("+landmarkName+-button").click(function(){
$("+landmarkName+-info").addClass("active-info")
});
Is something like this even possible?
Thanks in advance for all your answers.
EDIT: Here's the full HTML.
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button"></div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button"></div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Assuming you're not able to modify your HTML markup (in which case with use of CSS classes would be cleaner), a solution to your question would be as shown below:
// Assign same click handler to all buttons
$("#arch-of-triumph-button, #romanian-athenaeum-button, #palace-of-parliament-button")
.click(function() {
// Extract id of clicked button
const id = $(this).attr("id");
// Obtain corresponding info selector from clicked button id by replacing
// last occurrence of "button" pattern with info.
const infoSelector = "#" + id.replace(/button$/gi, "info");
// Add active-info class to selected info element
$(infoSelector).addClass("active-info");
});
Because each .landmark-button looks to be in the same order as its related .landmark-info, you can put both collections into an array, and then when one is clicked, just find the element with the same index in the other array:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
This does not rely on IDs at all - feel free to completely remove those from your HTML to declutter, because they don't serve any purpose now that they aren't being used as selectors.
Live snippet:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
.active-info {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button">click</div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button">click</div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Older answer, without knowing the HTML: You can extract the ID of the clicked button, slice off the button part of it, and then select it concatenated with -info:
$(".landmark-button").click(function() {
const infoSel = this.id.slice(0, this.id.length - 6) + 'info';
$(infoSel).addClass('active-info');
});
A much more elegant solution would probably be possible given the HTML, though.

jQuery to iterate through class elements, grab text, insert elsewhere

I need to programmatically extract titles within a webpage, inject anchor links right above those titles and then inject navigation links near the top of the page that will link to those anchors within the same page.
I need jQuery to select all headings with the class of 'iphorm-group-title’ and extract the text.
Above each heading, excluding the first heading, an anchor tag needs to be injected so that a visitor can link to that section of the page.
The text of each heading, excluding the first heading, needs to be injected before the first heading and linked to all the anchor tags that were injected in the previous step.
This form is generated by a plugin or I would just edit the HTML.
For reference, the page is located at:
http://mountpleasantmagazine.com/BestOfBallot/
Here is an example of the HTML as of now.
<div>
<div>
<div class="iphorm-group-title">VOTER INFO</div>
</div>
<div>
<div class="iphorm-group-title">SHOPPING & GOODS</div>
</div>
<div>
<div class="iphorm-group-title">FOOD & DRINK</div>
</div>
<div>
<div class="iphorm-group-title">ENTERTAINMENT & LEISURE</div>
</div>
</div>
Here is some JS that will grab the elements and loop through the text, which is the point where I'm stuck.
jQuery('.iphorm-group-title').each(function () {
console.log(jQuery(this).text());
});
Here is how the HTML is expected to look after injecting the code.
<div>
<div>
SHOPPING & GOODS | FOOD & DRINK | <a href="#entertainmentleisure">ENTERTAINMENT & LEISURE</ a>
</div>
<div>
<div class="iphorm-group-title">VOTER INFO</div>
</div>
<div>
<a name="shoppinggoods"></a>
<div class="iphorm-group-title">SHOPPING & GOODS</div>
</div>
<div>
<a name="fooddrink"></a>
<div class="iphorm-group-title">FOOD & DRINK</div>
</div>
<div>
<a name="entertainmentleisure"></a>
<div class="iphorm-group-title">ENTERTAINMENT & LEISURE</div>
</div>
</div>
I just made a code snippet for you hope so it's the exact what you needed.
var listElement=jQuery("<div id='menuList'></div>").insertBefore(".iphorm-elements");
jQuery(".iphorm-elements .iphorm-group-wrap:not(:first-child)")
.each(function() {
if (jQuery(this)
.not(".iphorm-group-wrap:first")) {
var heading = jQuery(this)
.find(".iphorm-group-title");
var headingName = heading.text()
.split(' ')
.join('')
.replace('&', '');
var lowerHeading = headingName.toLowerCase();
var anchorUrl = [lowerHeading.slice(0, 0), lowerHeading.slice(0)].join('');
var anchorText = heading.text();
var anchorLink=jQuery('<a name="' + anchorUrl + '"></a>')
.insertBefore(heading);
var anchorLink2=jQuery('' + anchorText + '' +"<span> | </span>")
.insertBefore(heading);
jQuery(listElement).append(anchorLink2);
}
});
jQuery("#menuList span:last-child").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="iphorm-elements">
<div class="iphorm-group-wrap">
<div class="iphorm-group-title-description-wrap">
<div class="iphorm-group-title">VOTER INFO</div>
</div>
</div>
<div class="iphorm-group-wrap">
<div class="iphorm-group-title-description-wrap">
<div class="iphorm-group-title">SHOPPING & GOODS</div>
</div>
</div>
<div class="iphorm-group-wrap">
<div class="iphorm-group-title-description-wrap">
<div class="iphorm-group-title">FOOD & DRINK</div>
</div>
</div>
<div class="iphorm-group-wrap">
<div class="iphorm-group-title-description-wrap">
<div class="iphorm-group-title">FOOD & DRINK</div>
</div>
</div>
<div class="iphorm-group-wrap">
<div class="iphorm-group-title-description-wrap">
<div class="iphorm-group-title">ENTERTAINMENT & LEISURE</div>
</div>
</div>
</div>

Remove words from <div> generated on load

I am working on a webpage for a family member, and most content is generated upon load.
My specific problem lies in a news-function, where you can add new products. Because of the way the website is built we have added a link to the news-item, in order to allow costumers to go directly to the product. ( link is "Se mere" )
Trouble is:
When adding the new item to the news-feed, all links and formatting disappears when its shown on the right side of the page. (This is where the code is from)
Therefore, i would like to remove the "Se mere" text from the right coloumn, in the div class = "NewsItemPreviewText"
Unfortunately, i cannot access that part of the code, so i cannot choose what and how its printet.
Here you can see original code that i have access to,
`<div id="RightColumn">{$Design.rightColumn}</div>`
and this is how the code looks when generated.
<div id="RightColumn">
<div id="pagenews-box">
<div id="pagenews-box-top">
<h2>Nyheder</h2>
</div>
<div id="pagenews-box-content"> <div class="NewsItemPreview NewsItem1">
<div class="NewsItemPreviewImg">
<a href="/nyheder/4-revitive-isorocker-/#4" title="Revitive Isorocker ">
<img src="/upload_dir/news/REVITIVEIX.w50.h50.crop.jpg" style="border:0px;" alt="Revitive
Isorocker ">
</a>
</div>
<div class="NewsItemPreviewContent" style="width:110px">
<div class="NewsItemPreviewDate">
<a href="/nyheder/4-revitive-isorocker-/#4" title="Revitive Isorocker "
class="NewsItemPreviewLink">Revitive Isorocker </a>
<br>
<div class="NewsItemPreviewDateCreated">26/11 2014 kl. 12:20
</div>
</div>
<div class="NewsItemPreviewText">
Årets julegavehit!
KUN 1795,-kr. hos os!
Se mere
</div>
</div>
</div>
</div>
<div id="pagenews-box-bottom">
</div>
</div>`
</div>
I hope you can help, please let me know if i have omitted any necessary details or code.
Using JQuery this can be done by targeting the container("NewsItemPreviewText") containing the text "Se mere" and removing it.
$('.NewsItemPreviewText:contains("Se mere")').each(function(){
$(this).html($(this).html().split("Se mere").join(""));
});
JSFiddle
You can remove it with jQuery.
http://jsfiddle.net/wilchow/pzrn88m4/
$(document).ready(function() {
$(".NewsItemPreviewText").text($(".NewsItemPreviewText").text().replace("Se mere", ""));
});
Hope this helps :)
$(':contains("Se mere")').each(function(){
$(this).html($(this).html().split("Se mere").join(""));
});

Mouseover text then Change Image not Working in IE8-below

I have a banner made out of JavaScript wherein when you hover a particular text the image in the banner changes.
I was wondering how to make it compatible in ie8..
I used this tutorial to come up with the js:
http://www.javascriptkit.com/script/script2/rolldifferent.shtml
I'm also trying to mouse out too then the image will change.
Here are the js codes:
<script type="text/javascript">function changeimage(towhat,url){if (document.images){document.images.targetimage.src=towhat.src gotolink=url}}functionwarp({window.location=gotolink}</script>
<script>var myimages=new Array()var gotolink="#"function preloadimages(){for (i=0;i<preloadimages.arguments.length;i++){myimages[i]=newImage()myimages[i].src=preloadimages.arguments[i]}}preloadimages("map_wm_hover.gif", "map_wm_hover2.gif","map_wm.gif")</script>
Here is the css:
<div id="base"><div id="mapcontainer"><img src="map_wm.gif" name="targetimage" border=0></div>
<div id="textcontainer"><div class="textboxinner1">8CCC REQUESTS/TALKBACK</div>
<div class="textboxinner2">Alice Springs 8952 7771</div>
<div class="textboxinner2">Tenant Creek 8952 7182</div>
<div class="textboxinner3"><span class="t3nonelink">...other contact details here</span></div>
I believe this is an issue with IE where animated gifs are not loaded properly in javascript. A workaround is to put the images in a hidden div in the HTML code instead of loading them in the script. A positive side-effect is that this greatly simplifies the javascript. See http://jsfiddle.net/5pZLT/7
HTML:
<DIV id=base>
<DIV id=mapcontainer><IMG border=0 name=targetimage src ="http://www.keencloudmedia.com/skybluekangaroo/map_wm.gif"> </DIV>
<DIV id=textcontainer>
<DIV class=textboxinner1><A onmouseover=changeimage(2,this.href)
href="index.html">8CCC REQUESTS/TALKBACK</A> </DIV>
<DIV class=textboxinner2><A onmouseover=changeimage(1,this.href)
href="index.html">Alice Springs 8952 7771</A> </DIV>
<DIV class=textboxinner2><A onmouseover=changeimage(0,this.href)
href="index.html">Tenant Creek 8952 7182</A> </DIV>
<DIV class=textboxinner3><SPAN class=t3nonelink>...other contact details <A
onmouseover=changeimage(2,this.href) href="index.html">here</A></SPAN>
</DIV></DIV></DIV><div id="hiddenImages" style="display: none">
<img src="http://www.keencloudmedia.com/skybluekangaroo/map_wm_hover.gif" name="hoverImage" />
<img src="http://www.keencloudmedia.com/skybluekangaroo/map_wm_hover2.gif" name="hoverImage2" />
<img src="http://www.keencloudmedia.com/skybluekangaroo/map_wm.gif" name="originalImage" />
</div>​
Javascript:
var gotolink = "#";
function changeimage(imageNumber, url) {
if (document.images) {
document.images.targetimage.src =
document.getElementById('hiddenImages').children[imageNumber].src;
gotolink = url;
}
}
By the way there were lots of ;s missing in your original code which would tend to stop it working.

Categories

Resources