How to clone and change id? - javascript

I need to clone the id and then add a number after it like so id1, id2, etc. Every time you hit clone you put the clone after the latest number of the id.
$("button").click(function() {
$("#id").clone().after("#id");
});

$('#cloneDiv').click(function(){
// get the last DIV which ID starts with ^= "klon"
var $div = $('div[id^="klon"]:last');
// Read the Number from that DIV's ID (i.e: 3 from "klon3")
// And increment that number by 1
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
// Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
var $klon = $div.clone().prop('id', 'klon'+num );
// Finally insert $klon wherever you want
$div.after( $klon.text('klon'+num) );
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id="cloneDiv">CLICK TO CLONE</button>
<div id="klon1">klon1</div>
<div id="klon2">klon2</div>
Scrambled elements, retrieve highest ID
Say you have many elements with IDs like klon--5 but scrambled (not in order). Here we cannot go for :last or :first, therefore we need a mechanism to retrieve the highest ID:
const all = document.querySelectorAll('[id^="klon--"]');
const maxID = Math.max.apply(Math, [...all].map(el => +el.id.match(/\d+$/g)[0]));
const nextId = maxID + 1;
console.log(`New ID is: ${nextId}`);
<div id="klon--12">12</div>
<div id="klon--34">34</div>
<div id="klon--8">8</div>

Update: As Roko C.Bulijan pointed out.. you need to use .insertAfter to insert it after the selected div. Also see updated code if you want it appended to the end instead of beginning when cloned multiple times. DEMO
Code:
var cloneCount = 1;;
$("button").click(function(){
$('#id')
.clone()
.attr('id', 'id'+ cloneCount++)
.insertAfter('[id^=id]:last')
// ^-- Use '#id' if you want to insert the cloned
// element in the beginning
.text('Cloned ' + (cloneCount-1)); //<--For DEMO
});
Try,
$("#id").clone().attr('id', 'id1').after("#id");
If you want a automatic counter, then see below,
var cloneCount = 1;
$("button").click(function(){
$("#id").clone().attr('id', 'id'+ cloneCount++).insertAfter("#id");
});

This is the simplest solution working for me.
$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");

This works too
var i = 1;
$('button').click(function() {
$('#red').clone().appendTo('#test').prop('id', 'red' + i);
i++;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="test">
<button>Clone</button>
<div class="red" id="red">
</div>
</div>
<style>
.red {
width:20px;
height:20px;
background-color: red;
margin: 10px;
}
</style>

I have created a generalised solution. The function below will change ids and names of cloned object. In most cases, you will need the row number so Just add "data-row-id" attribute to the object.
function renameCloneIdsAndNames( objClone ) {
if( !objClone.attr( 'data-row-id' ) ) {
console.error( 'Cloned object must have \'data-row-id\' attribute.' );
}
if( objClone.attr( 'id' ) ) {
objClone.attr( 'id', objClone.attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
}
objClone.attr( 'data-row-id', objClone.attr( 'data-row-id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
objClone.find( '[id]' ).each( function() {
var strNewId = $( this ).attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } );
$( this ).attr( 'id', strNewId );
if( $( this ).attr( 'name' ) ) {
var strNewName = $( this ).attr( 'name' ).replace( /\[\d+\]/g, function( strName ) {
strName = strName.replace( /[\[\]']+/g, '' );
var intNumber = parseInt( strName ) + 1;
return '[' + intNumber + ']'
} );
$( this ).attr( 'name', strNewName );
}
});
return objClone;
}

$('#cloneDiv').click(function(){
// get the last DIV which ID starts with ^= "klon"
var $div = $('div[id^="klon"]:last');
// Read the Number from that DIV's ID (i.e: 3 from "klon3")
// And increment that number by 1
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
// Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
var $klon = $div.clone().prop('id', 'klon'+num );
// Finally insert $klon wherever you want
$div.after( $klon.text('klon'+num) );
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

Related

How to Add +200ms to css animation-duration on click jQuery

There is a div with css animation
.mydiv {
animation: ticker 2000ms linear 0s infinite normal none running;
}
The animation-duration property is set to 2000ms
and im trying to change the speed of the animation with jquery
for example adding 200ms to the currentvalue
something like
$( "#speedup" ).click(function() {
var mydiv = $( ".mydiv" );
var val = mydiv.css('animation-duration');
$(".mydiv").css("animation-duration", val + "ms")+200;
});
The variable 'val' is not an integer (2s). You can't multiply with this value. You need to use parseInt() to return the integer (2).
$('#speedup').click(function(){
var mydiv = $( ".mydiv" );
var val = mydiv.css('animation-duration');
var newVal = (parseInt(val) * 1000); //parseInt(val) creates the integer 2. Multiply with 1000 to get 2000
mydiv.css({"animation-duration" : newVal - 200 + "ms"});
});
Edit: ParseFloat is even better. This way you can use toFixed to get the integer with 2 decimals.
https://jsfiddle.net/qcajbtz8/
$('#speedup').click(function(){
var mydiv = $( ".mydiv" );
var val = mydiv.css('animation-duration');
var newVal = (parseFloat(val).toFixed(2) * 1000);
mydiv.css({"animation-duration" : newVal - 200 + "ms"});
});
Try this.
var val = currentvalue;
$( "#speedup" ).click(function() {
var mydiv = $( ".mydiv" );
val = val + 200;
$(".mydiv").css("animation-duration", val + "ms");
});

Getting element ID's for if/else statements

Working on a project. I need the else statement to work but when I hit the submit button it just redirects to the "if"
<head>
<script>
var judgmentAmount = document.getElementById('judgmentAmount');
var amountCollected = document.getElementById('amountCollected');
function judgmentCalc() {
if( judgmentAmount - amountCollected < 10000 ) {
window.open( 'http://afjudgment.com' );
}else {
window.open( 'http://www.yahoo.com' );
}
}
</script>
</head>
<body>
<h1>Application</h1>
<p>I understand that this application neither obligates me to <b>Affirmative Judgment</b> nor does it obligate <b>Affirmative Judgment</b> to me.</p>
<h3>Judgment Information</h3>
<form>
<span>Do you have a case number?</span>
<input type="text" name="caseNumber" />
<span>Amount of Judgment</span>
<input type="text" name="judgmentAmount" id="judgmentAmount" />
<span>Amount collected to date</span>
<input type="text" name="amountCollected" id="amountCollected" />
<input type="submit" name="submitButton" onclick="judgmentCalc();" />
</form>
You need to access values of these input fields instead of directly working on dom elemens returned by document.getElementById(). You can get value of input using .value property.
var judgmentAmount = document.getElementById('judgmentAmount').value;
var amountCollected = document.getElementById('amountCollected').value;
move your variables inside the function so they are properly filled at the time of function execution, and add .value properties of the DOM elements.
try this:
function judgmentCalc() {
var judgmentAmount = document.getElementById('judgmentAmount').value;
var amountCollected = document.getElementById('amountCollected').value;
if( judgmentAmount - amountCollected < 10000 ) {
window.open( 'http://afjudgment.com' );
}else {
window.open( 'http://www.yahoo.com' );
}
}
You are only comparing the objects, you need to compare their values
var judgmentAmount = Number(document.getElementById('judgmentAmount').value);
var amountCollected = Number(document.getElementById('amountCollected').value);
Also, convert them to Number before comparison.
function judgmentCalc() {
var judgmentAmount = Number(document.getElementById('judgmentAmount').value);
var amountCollected = Number(document.getElementById('amountCollected').value);
if( judgmentAmount - amountCollected < 10000 ) {
window.open( 'http://afjudgment.com' );
}else {
window.open( 'http://www.yahoo.com' );
}
}
You're getting the HTML DOM elements here:
var judgmentAmount = document.getElementById('judgmentAmount');
var amountCollected = document.getElementById('amountCollected');
So in your judgementCalc method you need to get the values of those elements:
function judgmentCalc() {
// notice that we're using VALUE here:
if( judgmentAmount.value - amountCollected.value < 10000 ) {
window.open( 'http://afjudgment.com' );
}else {
window.open( 'http://www.yahoo.com' );
}
}
You need to operate with values of your elements:
function judgmentCalc() {
var judgmentAmount = +document.getElementById('judgmentAmount').value;
var amountCollected = +document.getElementById('amountCollected').value;
if( judgmentAmount - amountCollected < 10000 ) {
window.open( 'http://afjudgment.com' );
}
else {
window.open( 'http://www.yahoo.com' );
}
}
var judgmentAmount = document.getElementById('judgmentAmount') returns only a reference to element with ID "judgmentAmount". If you want to use element's value, you need to do this:
var judgmentAmount = document.getElementById('judgmentAmount').value.
The next step is calculating some amount. You need to convert string to int (with + operator)
typeof judgmentAmount; // "string"
typeof +judgmentAmount; // "number"
Demo
Please run the script below, it'll work fine:
<head>
<script>
function judgmentCalc() {
var judgmentAmount = document.getElementById('judgmentAmount').value;
var amountCollected = document.getElementById('amountCollected').value;
var exp = parseFloat(judgmentAmount) - parseFloat(amountCollected);
if( exp < 10000 ) {
window.open( 'http://afjudgment.com' );
} else {
window.open( 'http://www.yahoo.com' );
}
}
</script>
</head>
You have to compare the value of the input element, Please try the following
function judgmentCalc() {
var judgmentAmount = document.getElementById('judgmentAmount').value;
var amountCollected = document.getElementById('amountCollected').value;
if( (judgmentAmount - amountCollected) < 10000 ) {
window.open( 'http://afjudgment.com' );
} else {
window.open( 'http://www.yahoo.com' );
}
}
It may help you.

javascript forEach - add addEventListener on all buttons

I'm not so skilled with javascript so I'm looking for a little help.
I'm using a script found on Codrops (3D Grid Effect - http://tympanus.net/Development/3DGridEffect/).
All is working fine as expected but I'm trying to "modify" it for my needs.
Basically, I want to trigger the "effect" NOT clicking on the whole container but on a button placed inside it.
The structure I'm using is:
<section class="grid3d vertical" id="grid3d">
<div class="grid-wrap">
<div class="grid">
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
</div>
</div>
<div class="content">
<div>
<div class="dummy-img"></div>
<p class="dummy-text">Some text</p>
<p class="dummy-text">Some more text</p>
</div>
<div>
<!-- ... -->
</div>
<!-- ... -->
<span class="loading"></span>
<span class="icon close-content"></span>
</div>
</section>
<script>
new grid3D( document.getElementById( 'grid3d' ) );
</script>
And the script (js) is
/**
* grid3d.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2014, Codrops
* http://www.codrops.com
*/
;( function( window ) {
'use strict';
function grid3D( el, options ) {
this.el = el;
this.options = extend( {}, this.options );
extend( this.options, options );
this._init();
}
// any options you might want to configure
grid3D.prototype.options = {};
grid3D.prototype._init = function() {
// grid wrapper
this.gridWrap = this.el.querySelector( 'div.grid-wrap' );
// grid element
this.grid = this.gridWrap.querySelector( 'div.grid' );
// main grid items
this.gridItems = [].slice.call( this.grid.children );
// default sizes for grid items
this.itemSize = { width : this.gridItems[0].offsetWidth, height : this.gridItems[0].offsetHeight };
// content
this.contentEl = this.el.querySelector( 'div.content' );
// content items
this.contentItems = [].slice.call( this.contentEl.children );
// close content cross
this.close = this.contentEl.querySelector( 'span.close-content' );
// loading indicator
this.loader = this.contentEl.querySelector( 'span.loading' );
// support: support for pointer events, transitions and 3d transforms
this.support = support.pointerevents && support.csstransitions && support.csstransforms3d;
// init events
this._initEvents();
};
grid3D.prototype._initEvents = function() {
var self = this;
// open the content element when clicking on the main grid items
this.gridItems.forEach( function( item, idx ) {
item.addEventListener( 'click', function() {
self._showContent( idx );
} );
} );
// close the content element
this.close.addEventListener( 'click', function() {
self._hideContent();
} );
if( this.support ) {
// window resize
window.addEventListener( 'resize', function() { self._resizeHandler(); } );
// trick to prevent scrolling when animation is running (opening only)
// this prevents that the back of the placeholder does not stay positioned in a wrong way
window.addEventListener( 'scroll', function() {
if ( self.isAnimating ) {
window.scrollTo( self.scrollPosition ? self.scrollPosition.x : 0, self.scrollPosition ? self.scrollPosition.y : 0 );
}
else {
self.scrollPosition = { x : window.pageXOffset || docElem.scrollLeft, y : window.pageYOffset || docElem.scrollTop };
// change the grid perspective origin as we scroll the page
self._scrollHandler();
}
});
}
};
// creates placeholder and animates it to fullscreen
// in the end of the animation the content is shown
// a loading indicator will appear for 1 second to simulate a loading period
grid3D.prototype._showContent = function( pos ) {
if( this.isAnimating ) {
return false;
}
this.isAnimating = true;
var self = this,
loadContent = function() {
// simulating loading...
setTimeout( function() {
// hide loader
classie.removeClass( self.loader, 'show' );
// in the end of the transition set class "show" to respective content item
classie.addClass( self.contentItems[ pos ], 'show' );
}, 1000 );
// show content area
classie.addClass( self.contentEl, 'show' );
// show loader
classie.addClass( self.loader, 'show' );
classie.addClass( document.body, 'noscroll' );
self.isAnimating = false;
};
// if no support just load the content (simple fallback - no animation at all)
if( !this.support ) {
loadContent();
return false;
}
var currentItem = this.gridItems[ pos ],
itemContent = currentItem.innerHTML;
// create the placeholder
this.placeholder = this._createPlaceholder(itemContent );
// set the top and left of the placeholder to the top and left of the clicked grid item (relative to the grid)
this.placeholder.style.left = currentItem.offsetLeft + 'px';
this.placeholder.style.top = currentItem.offsetTop + 'px';
// append placeholder to the grid
this.grid.appendChild( this.placeholder );
// and animate it
var animFn = function() {
// give class "active" to current grid item (hides it)
classie.addClass( currentItem, 'active' );
// add class "view-full" to the grid-wrap
classie.addClass( self.gridWrap, 'view-full' );
// set width/height/left/top of placeholder
self._resizePlaceholder();
var onEndTransitionFn = function( ev ) {
if( ev.propertyName.indexOf( 'transform' ) === -1 ) return false;
this.removeEventListener( transEndEventName, onEndTransitionFn );
loadContent();
};
self.placeholder.addEventListener( transEndEventName, onEndTransitionFn );
};
setTimeout( animFn, 25 );
};
grid3D.prototype._hideContent = function() {
var self = this,
contentItem = this.el.querySelector( 'div.content > .show' ),
currentItem = this.gridItems[ this.contentItems.indexOf( contentItem ) ];
classie.removeClass( contentItem, 'show' );
classie.removeClass( this.contentEl, 'show' );
// without the timeout there seems to be some problem in firefox
setTimeout( function() { classie.removeClass( document.body, 'noscroll' ); }, 25 );
// that's it for no support..
if( !this.support ) return false;
classie.removeClass( this.gridWrap, 'view-full' );
// reset placeholder style values
this.placeholder.style.left = currentItem.offsetLeft + 'px';
this.placeholder.style.top = currentItem.offsetTop + 'px';
this.placeholder.style.width = this.itemSize.width + 'px';
this.placeholder.style.height = this.itemSize.height + 'px';
var onEndPlaceholderTransFn = function( ev ) {
this.removeEventListener( transEndEventName, onEndPlaceholderTransFn );
// remove placeholder from grid
self.placeholder.parentNode.removeChild( self.placeholder );
// show grid item again
classie.removeClass( currentItem, 'active' );
};
this.placeholder.addEventListener( transEndEventName, onEndPlaceholderTransFn );
}
// function to create the placeholder
/*
<div class="placeholder">
<div class="front">[content]</div>
<div class="back"></div>
</div>
*/
grid3D.prototype._createPlaceholder = function( content ) {
var front = document.createElement( 'div' );
front.className = 'front';
front.innerHTML = content;
var back = document.createElement( 'div' );
back.className = 'back';
back.innerHTML = ' ';
var placeholder = document.createElement( 'div' );
placeholder.className = 'placeholder';
placeholder.appendChild( front );
placeholder.appendChild( back );
return placeholder;
};
grid3D.prototype._scrollHandler = function() {
var self = this;
if( !this.didScroll ) {
this.didScroll = true;
setTimeout( function() { self._scrollPage(); }, 60 );
}
};
// changes the grid perspective origin as we scroll the page
grid3D.prototype._scrollPage = function() {
var perspY = scrollY() + getViewportH() / 2;
this.gridWrap.style.WebkitPerspectiveOrigin = '50% ' + perspY + 'px';
this.gridWrap.style.MozPerspectiveOrigin = '50% ' + perspY + 'px';
this.gridWrap.style.perspectiveOrigin = '50% ' + perspY + 'px';
this.didScroll = false;
};
grid3D.prototype._resizeHandler = function() {
var self = this;
function delayed() {
self._resizePlaceholder();
self._scrollPage();
self._resizeTimeout = null;
}
if ( this._resizeTimeout ) {
clearTimeout( this._resizeTimeout );
}
this._resizeTimeout = setTimeout( delayed, 50 );
}
grid3D.prototype._resizePlaceholder = function() {
// need to recalculate all these values as the size of the window changes
this.itemSize = { width : this.gridItems[0].offsetWidth, height : this.gridItems[0].offsetHeight };
if( this.placeholder ) {
// set the placeholders top to "0 - grid offsetTop" and left to "0 - grid offsetLeft"
this.placeholder.style.left = Number( -1 * ( this.grid.offsetLeft - scrollX() ) ) + 'px';
this.placeholder.style.top = Number( -1 * ( this.grid.offsetTop - scrollY() ) ) + 'px';
// set the placeholders width to windows width and height to windows height
this.placeholder.style.width = getViewportW() + 'px';
this.placeholder.style.height = getViewportH() + 'px';
}
}
// add to global namespace
window.grid3D = grid3D;
})( window );
Now, I'm aware that the "crucial" portion of the code where I have to look is:
// open the content element when clicking on the main grid items
this.gridItems.forEach( function(item, idx ) {
item.addEventListener( 'click', function() {
item._showContent( idx ); } ); } );
So, my question again: how to trigger the event when the div (button) class "click-me" is clicked on every "boxes"?
Thanks to all in advance (i'm struggling with it for hours...)
Have a look at the example here,
http://jsfiddle.net/y0mbn94n/
I have added some intialisation to get your particular classes
// get grid buttons and then make an iterable array out of them
this.gridButtons = this.el.querySelectorAll('button.btn-click-me');
this.gridButtonItems = [].slice.call(this.gridButtons);
and changed the function which iterates and adds a listener.
// open the content element when clicking on the buttonsItems
this.gridButtonItems.forEach(function (item, idx) {
item.addEventListener('click', function () {
self._showContent(idx);
});
});
If you want to call a callback function when the user clicks on a button:
var buttons = document.querySelectorAll('.btn-click-me');
for (var i = 0; i < buttons.length; i++) {
var self = buttons[i];
self.addEventListener('click', function (event) {
// prevent browser's default action
event.preventDefault();
// call your awesome function here
MyAwesomeFunction(this); // 'this' refers to the current button on for loop
}, false);
}
with the structure given
<div class="grid-wrap">
<div class="grid">
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
</div>
</div>
you just have to change the line you've said to:
item.children[0].addEventListener( 'click', function() {
as the btn-click-me would be the first child of each item.
If you would like a more generic solution you could use:
item.getElementsByClassName('btn-click-me')[0].addEventListener( 'click', function() {
where bnt-click-me would be the class of the button that you would want to bind the click event. Notice that [0] so you can select the very first item of the array, as getElementsByClassName will return one, even if there's only one element.
But if you say you're just starting with javascript y really recommend you using jQuery, it's selectors are much easier than vanilla javascript.

Add row to html table below the selected row when previous row has rowspan

I have the following code to add rows to a table using a context menu plugin so you can right click the cell you want to add the row below.
(function($){
function scanTable( $table ) {
var m = [];
$table.children( "tr" ).each( function( y, row ) {
$( row ).children( "td, th" ).each( function( x, cell ) {
var $cell = $( cell ),
cspan = $cell.attr( "colspan" ) | 0,
rspan = $cell.attr( "rowspan" ) | 0,
tx, ty;
cspan = cspan ? cspan : 1;
rspan = rspan ? rspan : 1;
for( ; m[y] && m[y][x]; ++x ); //skip already occupied cells in current row
for( tx = x; tx < x + cspan; ++tx ) { //mark matrix elements occupied by current cell with true
for( ty = y; ty < y + rspan; ++ty ) {
if( !m[ty] ) { //fill missing rows
m[ty] = [];
}
m[ty][tx] = true;
}
}
var pos = { top: y, left: x };
$cell.data( "cellPos", pos );
} );
} );
};
/* plugin */
$.fn.cellPos = function( rescan ) {
var $cell = this.first(),
pos = $cell.data( "cellPos" );
if( !pos || rescan ) {
var $table = $cell.closest( "table, thead, tbody, tfoot" );
scanTable( $table );
}
pos = $cell.data( "cellPos" );
return pos;
}
})(jQuery);
appendMe();
function appendMe() {
$('table.test td').find("em").remove()
$('table.test td').removeAttr("realCellEq").append(function(){
return "<em> " + $(this).cellPos().left + "</em>"
}).attr("realCellEq", function() {
return $(this).cellPos().left
});
}
$(function () {
$.contextMenu({
selector: 'table.test td',
items: {
"addRowBelow": {
name: "Add Row Below",
callback: function (key, options) {
$(this).parents("tr").after("<tr class='freshAdd'></tr>");
$(this).parents("tr").find("td").each( function() {
var thisRowSpan = ($(this).attr("rowspan")) ? $(this).attr("rowspan") : 1;
if(thisRowSpan > 1) {
$(this).attr("rowspan", (parseInt($(this).attr("rowspan"),10)+1));
} else {
$(this).clone().appendTo("tr.freshAdd");
}
});
$("tr.freshAdd").find("td").html("");
$("tr.freshAdd").removeClass("freshAdd");
appendMe();
}
}
}
});
});
The trouble is i can't work out what I need to do to take into consideration rowspans.
Here's a jsfiddle to explain what I mean.
http://jsfiddle.net/many_tentacles/sqjak/1/
The reason you are not able to add a fresh cell, using the the freshly added cells is , those freshly added cells contain a class called context-menu-active which prohibits the functions you have written to add the cells.
You need to do a small change inside callback like :
$(".context-menu-active").removeClass('context-menu-active');
This removes the class from any freshly added cell and hence it becomes usable again.
Look at the updated fiddle : http://jsfiddle.net/Q5PgG/
Your parents("tr") was not targeting previous parents so i have added prev() each() function , you can do it this way:
$(this).parent("tr").after("<tr class='freshAdd'></tr>");
$(this).parent("tr").prev().find("td").each( function() {
var thisRowSpan = ($(this).attr("rowspan")) ? $(this).attr("rowspan") : 1;
if(thisRowSpan > 1) {
$(this).attr("rowspan", (parseInt($(this).attr("rowspan"),10)+1));
}
})
$(this).parent("tr").find("td").each( function() {
var thisRowSpan = ($(this).attr("rowspan")) ? $(this).attr("rowspan") : 1;
if(thisRowSpan > 1) {
$(this).attr("rowspan", (parseInt($(this).attr("rowspan"),10)+1));
} else {
$(this).clone().appendTo("tr.freshAdd");
}
Working demo Fiddle

How to create link on image using Javascript

<div id="mydiv">
<img src="myimage.jpg" />
</div>
<script language="javascript">
var a=document.createElement('a');
a.href='http://mylink.com';
document.getElementById('mydiv').appendChild(a);
</script>
The script doesn't work to create link on image
<div id="mydiv">
<img src="myimage.jpg" />
</div>
You are putting the link after the image.
You need to move the image so it is inside the link.
var image = document.getElementById('mydiv').getElementsByTagName('img')[0];
a.appendChild(image);
<div id="mydiv">
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/4/4d/Cat_November_2010-1a.jpg/220px-Cat_November_2010-1a.jpg" />
</div>
<script language="javascript">
var a=document.createElement('a');
a.href='http://mylink.com';
var image = document.getElementById('mydiv').getElementsByTagName('img')[0];
b=a.appendChild(image);
document.getElementById('mydiv').appendChild(a);
</script>
Thank's for the idea. this work
Here is a solution that doesn't need the additional div and puts a link around every image within the HTML page:
<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script type="text/javascript" charset="utf8">
$(document).ready(function(){
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
var image = images[i];
var parentElement = image.parentElement;
var a = document.createElement('a');
a.href = image.getAttribute('src');
a.appendChild(image);
parentElement.appendChild(a);
}
});
</script>
For single images
Where you can pass the image by element object, ID, or the first src substring match. Takes an optional target attribute, like "_blank". No jQuery required.
// By img element object
// (used by the functions below)
var addImageLink = function( elem, target ){
if( !elem || !( 'tagName' in elem ) ){ return; }
var image = elem;
var parent = image.parentElement;
var a = document.createElement( 'a' );
a.href = image.getAttribute( 'src' );
if( target ){ a.setAttribute( 'target', target ); }
a.appendChild( image );
parent.appendChild( a );
};
// By img element id
// <img src="images/gallery/1.jpg" id="image1" />
// <script> addImageLinkById( 'image1' ); </script>
var addImageLinkById = function( id, target ){
addImageLink( document.getElementById( id ), target );
};
// By img element src (first match)
// <img src="images/gallery/1.jpg"/>
// <script> addImageLinkBySrc( '/1.jpg' ); </script>
var addImageLinkBySrc = function( src, target ){
var image, images = document.getElementsByTagName( 'img' );
if( typeof src == 'undefined' ){ src = ''; }
for( var i = 0; i < images.length; i++ ){
if( images[ i ].src.indexOf( src ) < 0 ){ continue; }
addImageLink( images[ i ], target ); return;
}
};
For looping through all images
This solution puts a link around every image. It's an expanded version of Falko's answer.
Doesn't use jQuery
Optionally whitelist images by href substring, like "images/gallery/"
Specify an optional target attribute, like "_blank"
Won't skip the second half of the images(I experienced this issue when trying his code, but it could be something I did wrong)
var addImageLinks = function( filter, target ){
var parent, a, image;
var images = document.getElementsByTagName( 'img' );
var hasTarget = ( typeof target != 'undefined' );
var hasFilter = ( typeof filter != 'undefined' );
for( var i = 0; i < images.length; i++ ){
image = images[ i ];
if( hasFilter && ( image.src.indexOf( filter ) < 0 ) ){ continue; }
// Skip over already-wrapped images, by adding an attribute
if( image.getAttribute( 'data-wrapped-link' ) ){ continue; }
image.setAttribute( 'data-wrapped-link', '1' );
// Add the link
parent = image.parentElement;
a = document.createElement( 'a' );
a.href = image.getAttribute( 'src' );
if( hasTarget ){ a.setAttribute( 'target', target ); }
a.appendChild( image );
parent.appendChild( a );
// We inserted a "new" image, so go back one step so we don't miss any
// (due to being inside the "i < images.length" loop)
i--;
}
};
// Then:
// <img src="images/gallery/a.jpg"/>
// <img src="images/gallery/b.jpg"/>
// <img src="images/gallery/c.jpg"/>
// <img src="images/icons/a.gif"/> <- ignored
// Near bottom of the page (or in an onLoad handler, etc):
// </script> addImageLinks( 'images/gallery/', '_blank' ); </script>

Categories