How to create a div element out side the selected html element - javascript

The following tag is static element
<img src="http://www.jqueryscript.net/demo/Easy-Image-Morphing-Effect-with-jQuery-Canvas-morphing-js/img/pic.jpg" height="200" width="200" alt="">
and I want to create a div tag around the img tag dynamically, like below
<div class="dycls">
<img src="http://www.jqueryscript.net/demo/Easy-Image-Morphing-Effect-with-jQuery-Canvas-morphing-js/img/pic.jpg" height="200" width="200" alt="">
</div>
I tried the below code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js" type="text/javascript"></script>
<img src="http://www.jqueryscript.net/demo/Easy-Image-Morphing-Effect-with-jQuery-Canvas-morphing-js/img/pic.jpg" height="200" width="200" >
<script>
$(document).ready(function(){
$("img").prepend("<div class="dycls">");
$("img").append("</div>");
});
</script>

use .wrap
$(document).ready(function(){
$("img").wrap('<div class="dycls" />');
});
Using prepend()/append() does not work like string concatenation, also they add the passed element as children of the calling element

prepend/append will not work in this case. Use wrap()
Wrap an HTML structure around each element in the set of matched elements.
var myEl = $('<div />').addClass('dycls');
$('img').wrap(myEl);

Related

Switch Image By Adding Text Before File Extension

I Hope you can help me.
When I click button it adds night before file extension ex.(interior-1.jpg to interior-1-night) but it only affects the first image which is interior-1.jpg.
What I want is to add "night" text before the file extension of all images under the "image" ID.
Here is my html code
<button onclick="changeMode()">switch</button>
<img id="image" src="interior-1.jpg"/>
<img id="image" src="interior-2.jpg"/>
<img id="image" src="interior-3.jpg"/>
<img id="image" src="interior-4.jpg"/>
<img id="image" src="interior-5.jpg"/>
Here is my javascript code
<script>
function changeMode() {
var filename = document.getElementById("image").src;
var modfilename = filename.replace(/(\.[\w\d_-]+)$/i, '-night$1');
document.getElementById("image").src = modfilename;
</script>
}
You should never use same id name on elements in the dom. Instead use same class name. To apply the src on all the img tag get all the tags using document.getElementsByClassName. Iterate over each element and change the src using a forEach loop
function changeMode() {
var filename = document.getElementsByClassName("image");
var a = '';
Object.values(filename).forEach((e) => {
a = e.src;
var modfilename = a.replace(/(\.[\w\d_-]+)$/i, '-night$1');
e.src = modfilename;
})
}
<button onclick="changeMode()">switch</button>
<img class="image" src="interior-1.jpg" />
<img class="image" src="interior-2.jpg" />
<img class="image" src="interior-3.jpg" />
<img class="image" src="interior-4.jpg" />
<img class="image" src="interior-5.jpg" />
The problem is that you are getting your element by GetElementById which only returns one element. You should change the id tag to name like this:
<img name="image" src="interior-1.jpg"/>
Then you should be able to retrieve all the elements using var els = document.getElementsByName('image');
now you need to change their file names, so
for (let i = 0; i<els.length; i++){
els[i].src = els[i].src.replace(/(\.[\w\d_-]+)$/i, '-night$1');
}
Here is my two cents. Use classes. This way you can query multiple elements instead of just one. Then apply your changes to each element using, in this case, a forEach.
The elements returend from document.querySelectorAll is a nodeList. That's why I use Array.prototype.forEach.call.
function changeMode() {
const imageNodes = document.querySelectorAll(".image");
Array.prototype.forEach.call(imageNodes, (node) => {
let modfilename = node.src.replace(/(\.[\w\d_-]+)$/i, '-night$1');
node.src = modfilename
})
}
<button onclick="changeMode()">switch</button>
<img class="image" src="interior-1.jpg"/>
<img class="image" src="interior-2.jpg"/>
<img class="image" src="interior-3.jpg"/>
<img class="image" src="interior-4.jpg"/>
<img class="image" src="interior-5.jpg"/>

This.href is always undefined in javascript

I'm trying to make a simple gallery sing javascript (no jQuery). This is my html code
<section>
<div class="gallery" align="center">
<figure>
<p id="imgTitle">Les frères Sherlockooooooo</p>
<img src="../images/gallery/gal1.jpg" aligne="center" width="600" id="grande" 1px solid/>
</figure>
<article class="petite">
<script>
for (var i=1; i<11 ; i++)
document.write(' <img src="../images/gallery/thumbnails/gal' +i+ '_thumb.jpg" alt="gallery" class="thumbnails">');
</script>
</article>
<hr style="border-bottom: dotted 1px;"> </hr>
</div>
</section>
and this is my javascript code
window.onload=pageLoaded;
function pageLoaded() {
for (var i = 0; i < 11; i++) {
document.getElementsByClassName("thumbnails")[i].onclick=change_img;
}
}
function change_img() {
document.getElementById("grande").src=this.href;
// beyond this part is experimental
// end of experiment
}
What I want to make is to change the big image (the id is "grande") with another image by clicking the thumbnail. There is already a href inside the thumbnail, I expected a that the big image would change by changing the source of the big image with the href from the thumbnail, it turns out that only blank image showed up and it says that it's undefined. How to fix his? thanks in advance
You're referencing .thumbnails elements which are the <img> tag within your <a> tags. Your <a> tag contains the href attribute and their child tag contain a src attribute.
If you want the href tag, you'd need to assign the class of thumbnails to the <a> tag instead of the child or assign it it's own class name and reference that within your function.
<a href="../images/gallery/gal'+i+'.jpg" onclick="return false;">
<img class="thumbnails"src="../images/gallery/thumbnails/gal' +i+ '_thumb.jpg" alt="gallery">
// ^-- this tag doesn't contain a href attribute
</a>
Amending your <a> tags to this should fix your issue (without having to modify anything else in your code):
// v-- class added here instead
<a class="thumbnails" href="../images/gallery/gal'+i+'.jpg" onclick="return false;">
<img src="../images/gallery/thumbnails/gal' +i+ '_thumb.jpg" alt="gallery">
</a>

Using JSON to retrieve different id from data base

I have an HTML img tag with an empty src and I use JSON and jquery to retrieve the src of the img from the database when the user hovers over a parent span that contain the img tag. The problem is when I retrieve the src with JSON everything is fine and the image src is retrieved but I a loop set for this span in the very same page, so when the first image is already retrieved it's src is applied for the other looped span images. It is like retrieving the same id of the first image for the other different looped images that suppose to have different id for different content image contents.
here's is my code :
$(document).ready(function(){
$('#key').hover(function(){
var id=$('#im').attr('value');
$.post('getjson.php',{id:id},function(data){
$('img').attr('src',data.user_img);
},'json');
});
});
Here is the HTML
{loop="data"} <span class="foo" id="key">{$value.user_key}</span> <span class="foo">
<img alt="ther is an image here" src="" value="{$value.id}" id="im"/></span>
The problem is that you have duplicated IDs on your page. So, $('#key') will always return the first DIV with the id key, the same for $('#im'). Instead this $('img') will select all images on your page. Here is a demo to illustrate the problem:
console.log("$('#key') count:"+$('#key').length);
console.log("$('#img') count:"+$('#key').length);
console.log("$('img') count:"+$('img').length);
$('#key').hover(function(){
console.log("ID hovered: "+$('#im').attr('value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="key"> Div 1
<img src="" id="im" value="1" />
</div>
<div id="key"> Div 2
<img src="" id="im" value="2" />
</div>
<div id="key"> Div 3
<img src="" id="im" value="3" />
</div>
<div id="key"> Div 4
<img src="" id="im" value="4" />
</div>
To solve that you need to use another selector, for example, use a class:
$(document).ready(function(){
$('.my-selector').hover(function(){
//This will select all images inside 'this' (hovered .key)
var img = $('img', this);
$.post('getjson.php',{id : img.attr('value')},function(data){
img.attr('src',data.user_img);
},'json');
});
});
HTML:
{loop="data"} <div class="my-selector"> <!-- add parent div -->
<span class="foo" id="key">{$value.user_key}</span>
<span class="foo">
<img alt="ther is an image here" src="" value="{$value.id}" id="im"/>
</span>
</div>
Try changing
$('img').attr('src',data.user_img);
to
$("img[value='"+ id +"']").attr('src',data.user_img);
It is because you are setting the source to all images on the page.
$('img') should be replaced with $('#key')
in your case the code should be :
$(document).ready(function(){
$('#key').hover(function(){
var img = this;
var id=$('#im').attr('value');
$.post('getjson.php',{id:id},function(data){
$(img).attr('src',data.user_img);
},'json');
});
});

Access an html node in javascript

I have following html code.
<div id="polaroid">
<figure>
<img src="assets/polaroid01.jpg" width="200" height="200" alt="Red mushroom" />
<figcaption>Pretty red mushroom</figcaption>
</figure>
<figure>
<img src="assets/polaroid02.jpg" width="200" height="200" alt="Rainbow near Keswick" />
<figcaption>Rainbow near Keswick</figcaption>
</figure>
<figure>
<img src="assets/polaroid03.jpg" width="200" height="200" alt="An old tree" />
<figcaption>Nice old tree</figcaption>
</figure>
</div><!--end polaroid-->
In this i want to store all the image tags in an array. I know, I can access the figure tags like this.
var images= document.getElementById('gall').getElementsByTagName('figure');
But i don't know how to access the image tag.
I tried this.
document.getElementById('gall').getElementsByTagName('figure').getElementsByTagName('img');
But this doesn't work.
In this case it's more convenient to use querySelectorAll:
var images = document.querySelectorAll('#gall figure img');
You mean like this:
var images= document.getElementById('gall').getElementsByTagName('figure');
images.getElementsByTagName("img");
This is possible if you use JQuery. Simply Do This.
Include Jquery Library (any version).
select image : $("#polaroid img").(any action);
Example:
put this above your code:
<script src="../js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#polaroid img").css("border", "1px solid #000000");
});
</script>

Access all items under specific div in javascript

Hi i want to access all images under some specific div in javascript.My code is :
<div id="image-container" style="background-image:url(loading.gif)">
<div class="fade-box" id="image-1"><img src="2bscene-logo.gif" alt="" width="330" height="108" border="0" /></div>
<div class="fade-box" id="image-2" style="display: none;"><img src="streetgallery-logo.gif" alt="" width="330" height="108" border="0" /></div>
<div class="fade-box" id="image-3" style="display: none;"><img src="g4m-logo.gif" alt="" width="330" height="108" border="0" /></div>
</div>
While my js code is :
var image_slide = new Array('image-1', 'image-2', 'image-3');
I want to get all DIVs based on id dynamically, not having a predefined array. How can I do that?
By pure javascript, you can try:
var arr = document.querySelectorAll('#image-container img');
for(var i=0;i<arr.length;i++){
console.log(arr[i].getAttribute('src'))
}
On browsers that support querySelectorAll. (IE8 and up, modern versions of others, not IE7 and down.) - As mentioned in the comment by T.J. Crowder
With JavaScript, you can do this easily with the DOM:
var container = document.getElementById("image-container");
var child;
var image_slide = [];
for (child = container.firstChild; child; child = child.nextSibling) {
if (child.id && child.nodeName === "DIV") {
image_slide.push(child.id);
}
}
Live Example | Source
Note that the code above must be run after the elements are already in the DOM. The best way to ensure that is to put the script tag below them in the page (just before the closing </body> element is good).

Categories

Resources