creating a link to images - javascript

I am trying to create a jquery code which can wrap an img tag with a link:
My code is like this:
http://prntscr.com/iuw6hc
I will paste my HTML here but basically it is a loop of many items showing within each col.
<div class="car-item gray-bg text-center first" style="height: 357px;">
<div class="car-image">
<img class="img-responsive" src="http:///wp-content/uploads/2018/03/20180214_090633-265x190.jpg" alt="" width="265" height="190">
<div class="car-overlay-banner">
<ul>
<li><i class="fa fa-link"></i></li>
I am trying like this:
var wrapped = false;
var original = $(".img-responsive");
$(".img-responsive").click(function(){
if (!wrapped) {
wrapped = true;
var gURL = $('.car-overlay-banner').find('a').attr('href');
$(".img-responsive").wrap("");
}
});
$(".img-responsive").click(function(){
if (wrapped) {
wrapped = false;
$(".img-responsive").parent().replaceWith(original);
}
});
Trying to use a href of car overlay to apply to the image too.

jQuery provides a method named "wrap()", which can be used to insert any HTML structure in set of matched elements. In simple words, if you want put wrapper around your div element then you can use wrap() method. For example, you have a div with ID "Child".
<div id="Child"></div>
And want to wrap this div with any parent then you can use "wrap()" method to insert HTML.
$('#Child').wrap('<div id="Parent"></div>');
<div id="parent">
<div id="child"></div>
</div>
Same way, we will use the wrap() method to insert hyperlink to image tag so that the image becomes clickable. See below.
$(document).ready(function() {
$("#imgLogo").wrap('');
});
In this example, I have used ID as selector but you can use class selector to find all the images with same class and then wrap them with tag. You can also assign target="_blank" in the above tag to open the link in new window.

I think you need code like this?
var wrapped = false;
var original = $(".img-responsive");
$(".img-responsive").click(function(){
if (!wrapped) {
var wrapped = true;
// find link href in .car-image(img-responsive's parent)
var gURL = $(this).parent().find('a').attr('href');
// use $(this) instead of $(".classname") to apply link only clicked image
$(this).wrap("");
}
});
$(".img-responsive").click(function(){
if (wrapped) {
var wrapped = false;
$(this).parent().replaceWith(original);
}
});

Related

Insert html icon within a div with .before method

In this case,
I have some div like:
<div class="topImg">
<div class="topImgIcon">
<img src="img/bbbbb.png" class="topImgIcon"><span class="tittle">Chat Window</span>
</div>
</div>
And I want to insert this img link with one icon within this div. Is one X to close the windows but show some html code like form.
See my jQuery code:
var myDivImg = $( "<div class="topImg"></div>" )
$(document).ready(function() {
$("#maisinfo").before(myDivImg, '<a class="imgClose" href="javascript:window.close()"><img src="img/close.png"></a>');
$("#maisinfo").hide();
$("#show").bind("click",function(){
$("#maisinfo").slideToggle("slow");
return false;
});
});
I want to insert the html: <a class="imgClose" href="javascript:window.close()"><img src="img/close.png"></a> within .before() inside the div topImg in my HTML. I try create the div inside .before() but, jQuery create other same div.
Someone can help me please and make some explanation for I understand what I did wrong?
If you want to add something inside the DIV, you use .prepend() or .append(), depending on whether you want it at the beginning or end. .before() puts it outside the DIV, right before it.
$("#topDiv").prepend('<a class="imgClose" href="javascript:window.close()"><img src="img/close.png"></a>');
$(document).ready(function() {
$(".topImg").append("<div id='maisinfo'></div>");
$("#maisinfo").before('<a class="imgClose" href="javascript:window.close()"><img src="img/close.png"></a>');
$("#maisinfo").hide();
$("#show").bind("click",function(){
$("#maisinfo").slideToggle("slow");
return false;
});
});
</script>
<div class="topImg">
<div class="topImgIcon">
<img src="img/bbbbb.png" class="topImgIcon"><span class="tittle">Chat Window</span>
</div>
</div>
You could insert the div with ".html('xxx')" or with .append/prepend('xxx').
$(document).ready(function() {
var myDivImg = $( "<div class="topImg"></div>" );
// or var myDivImg=$('.topImg'); // => if the element exists
var myInsertDiv='<a class="imgClose" href="javascript:window.close()"><img src="img/close.png"></a>';
// first method
myDivImg.html( myInsertDiv ); // replace all html in this div with the content from "myInsertDiv"
//second method
myDivImg.append( myInsertDiv );// add the html from "myInsertDiv" as last child in your "myDivImg"
//or
myDivImg.append( myInsertDiv );// add the html from "myInsertDiv" as first child in your "myDivImg"
});
EDIT:
to close your div use something like this
$('body').on('click','.imgclose',function(){
$('.topImg').slideUp('slow');//close your parent-main div
return false;
});

Showing div using anchor in URL

I am using the jQuery-collapse plugin to hide/show the body content of posts, and want each post to also be accessible by URL.
<div id="<?php the_slug(); ?>" data-collapse>
<div id="collapse">
// Toggle content
</div>
<div class="main-content">
// Hidden content
</div>
</div>
The method I am trying is to call the post slug as the post ID (so I can use #the_slug in the url), find it, and then give the first child of the collapser the class "open" (which the plugin should recognise). As follows:
window.onload = function() {
var hash = window.location.hash;
if(hash != "") {
var id = hash.substr(1);
var d = document.getElementById(id);
d.firstChild.className = "open";
}
};
It does work insofar as the class is applied to the first child, but the plugin doesn't acknowledge it (it does if I add class="open" to the markup).
Any help in understanding why / other options much appreciated.
The problem is that the lib does not listen to classname changes.
Fron the API of the plugin
$(d).children( ).eq(0).trigger("open");
Use this code instead of className assignment.
If you use jQuery, you can do:
if(hash != "") {
$(hash).addClass("open");
}

javascript - how to get img tags from any element?

I want to get img tags attribute values from any element, img tags could be more than 1, and also can be randomized.
like,
<div> hellow <img src='icons/smile.png' title=':)'> how are u <img src='icons/smile2.png' title=':D'></div>
I want to grab their title attribute values and then want to store in some var currentHTML; with all existing div data.
and then insert into any element just like $('#div').html(currentHTML);
and output should be like this,
hellow :) how are u :D
How can I do this?
Thanks in advance.
Try this:
$("img").each(function()
{
$(this).replaceWith($(this).prop("title"));
});
Fiddle. Its just looping through each image and replacing it (with replaceWith()) with its own title attribute.
UPDATE:
Things got more complex. Check this snippet:
// The text result you want
var currentHTML = "";
// Instead of search for each image, we can search of elements that
// contains images and you want to get their text
$(".images").each(function()
{
// Check note #1
var cloned = $(this).clone().css("display", "none").appendTo($("body"));
// Here we select all images from the cloned element to what
// we did before: replace them with their own titles
cloned.find("img").each(function()
{
$(this).replaceWith($(this).prop("title"));
});
// Add the result to the global result text
currentHTML+= cloned.html();
});
// After all, just set the result to the desired element's html
$("#div").html(currentHTML);
Note #1: Here is what is happening in that line:
var cloned = here we create a var which will receive a cloned element;
the cloned element will the current element $(this).clone();
this element must be hidden .css("display", "none");
and then appended to the document's body .appendTo($("body"));.
Note that in your initial html, the div containing the images received the class images:
<div class="images"> hellow <img src='icons/smile.png' title=':)' /> how are u <img src='icons/smile2.png' title=':D' /></div>
So you can do that on more than one element. I hope this helps.
Here's a neat little function you can reuse.
$(function(){
function getImageReplace($el) {
var $copy = $el.clone();
$copy.find('img').each(function(){
$(this).replaceWith($(this).attr('title'));
});
return $copy.text();
}
//now you can use this on any div element you like
$('#go').click(function() {
alert(getImageReplace($('div')));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div> hellow <img src='icons/smile.png' title=':)'> how are u <img src='icons/smile2.png' title=':D'></div>
<button id='go'>Convert images</button>

jQuery select the function selector

I'm trying to achieve something inside a function, to actually access the parent selector.
Here is a small snippet of my HTML code:
<div class="module-row module-tab pull-right" id="modtab-sql_net">
<img src="images/icons/icon-orangebox-plus.png" class="modtab-toggle">
</div>
<div id="tab-module-row-1">
</div>
<div class="module-row module-tab pull-right" id="modtab-sql_dss">
<img src="images/icons/icon-orangebox-plus.png" class="modtab-toggle">
</div>
<div id="tab-module-row-2">
</div>
Here is the jQuery script I tried:
$('div[id^="modtab-"]').click(function(){
$(this).next('div[id^="tab-module-row"]').toggle(function(){
$(this).next('.modtab-toggle').toggle_switch.attr("src").replace("plus", "minus");
// The above line is incorrect. I need to change img attr for the class which is inside the div being clicked
});
});
Now, I want to actually change the image icon from a "plus" to a "minus" (the filenames are kept such).
I need to change $(this).next('.modtab-toggle') in the code to something that can work.
Please do NOT suggest to simply access the class using $('.modtab-toggle') as I have multiple such div tags in the code. It won't work out that way.
Thanks for any help.
Try this:
$('div[id^="modtab-"]').click(function(){
$(this).find('.modtab-toggle').attr("src", function(i, attr){
var o = this.src.indexOf('plus') > -1 ? this.src.replace('plus', 'minus') : this.src.replace('minus', 'plus');
return o;
});
});
See the Demo # Fiddle
try something like this
$('div[id^="modtab-"]').click(function(){
var $this = $(this);// clicked div
$this.next('.tab-module-row').toggle(function(){
$this.find('.modtab-toggle').toggle_switch.attr("src").replace("plus", "minus");
});
});
Note: you should use class instead of id because it should be unique
#tab-module-row ->.tab-module-row
EDITED ANSWER
$('div[id^="modtab-"]').click(function(){
var $this = $(this);// clicked div
$this.next('div[id^="tab-module-row"]').toggle(function(){
var img = $this.find('.modtab-toggle'); // your image object
// your condition to check which image to display will goes here.
});
});
change $(this).next('.modtab-toggle') to $(this).find('.modtab-toggle') to make it work.
See find() docs here

How to Reduce Size of This jQuery Script and Make it More Flexible?

I just created script that shows/hides (toggles) block of HTML. There are four buttons that each can toggle its HTML block. When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button... it hides that HTML block and shows new one.
Here is what I have at the moment:
$('.btn_add_event').click( function() {
$('.block_link, .block_photos, .block_videos').hide();
$('.block_event').toggle();
});
$('.btn_add_link').click( function() {
$('.block_event, .block_photos, .block_videos').hide();
$('.block_link').toggle();
});
$('.btn_add_photos').click( function() {
$('.block_event, .block_link, .block_videos').hide();
$('.block_photos').toggle();
});
$('.btn_add_videos').click( function() {
$('.block_event, .block_link, .block_photos').hide();
$('.block_videos').toggle();
});
Any ideas how to reduce code size? Also, this script isn't very flexible. Imagine to add two new buttons and blocks.
like Sam said, I would use a class that all the blocks share, so you never have to alter that code. Secondly, you can try 'traversing' to the closest block, therefore avoiding it's name. That approach is better than hard coding each specific block, but if the html dom tree changes you will need to refactor. Last, but best, you can pass in the class name desired block as a variable to the function. Below is something you can copy paste that is close to what you started with.
$('.myAddButtonClass').click( function() {
$('.mySharedBlockClass').filter(':visible').hide();
//find a good way to 'traverse' to your desired block, or name it specifically for now.
//$(this).closest(".mySharedBlockClass").show() complete guess
$('.specificBlockClass').show();
});
I kept reading this "When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button" thinking that my eyes were failing me when Its just bad English.
If you want to make it more dynamic, what you can do is add a common class keyword. Then
when the click event is raise. You can have it loop though all the classes that have the
keyword and have it hide them all (except the current one that was clicked) and then show the current one by using the 'this' keyword.
you can refer below link,
http://chandreshmaheshwari.wordpress.com/2011/05/24/show-hide-div-content-using-jquery/
call function showSlidingDiv() onclick event and pass your button class dynamically.
This may be useful.
Thanks.
try this
$('input[type=button]').click( function() {
$('div[class^=block]').hide(); // I resumed html block is div
$(this).toggle();
});
Unfortunatly I couldn't test it, but if I can remember right following should work:
function toogleFunc(clickObject, toogleTarget, hideTarget)
{
$(clickObject).click(function()
{
$(hideTarget).hide();
$(toogleTarget).toggle();
});
}
And the call:
toogleFunc(
".btn_add_videos",
".block_videos",
".block_event, .block_link, .block_photos"
);
and so far
Assuming the buttons will only have one class each, something like this ought to work.
var classNames = [ 'btn_add_event', 'block_link', 'block_photos', 'block_videos' ];
var all = '.' + classNames.join(', .'); // generate a jquery format string for selection
$(all).click( function() {
var j = classNames.length;
while(j--){
if( this.className === classNames[j] ){
var others = classNames.splice(j, 1); // should leave all classes but the one on this button
$('.' + others.join(', .')).hide();
$('.' + classNames[j]).toggle();
}
}
}
All the buttons have the same handler. When the handler fires, it checks the sender for one of the classes in the list. If a class is found, it generates a jquery selection string from the remaining classes and hides them, and toggles the one found. You may have to do some checking to make sure the strings are generating correctly.
It depends by how your HTML is structured.
Supposing you've something like this
<div class="area">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
...
<div class="sender">
<a class="one"></a>
<a class="two"></a>
<a class="three"></a>
</div>
You have a class shared by the sender and the target.
Your js would be like this:
$('.sender > a').click(function() {
var target = $(this).attr('class');
$('.area > .' + target).show().siblings().hide();
});
You show your real target and hide its siblings, which aren't needed.
If you put the class postfixes in an array, you can easily make this code more dynamic. This code assumed that it doesn't matter in which order toggle or hide are called. If it does matter, you can just remember the right classname inside the (inner) loop, and toggle that class after the loop.
The advantage to this approach is that you can extend the array with an exta class without needing to modifying the rest of the code.
var classes = new Array('videos', 'event', 'link', 'photos');
for (var i = 0; i < classes.length; ++i)
{
$('.btn_add_' + classes[i]).click(
function()
{
for (var j = 0; j < classes.length; ++j)
{
if (this.hasClass('btn_add_' + classes[j]))
{
$('.block_' + classes[j]).toggle();
}
else
{
$('.block_' + classes[j]).hide();
}
}
});
}
You could make this code more elegant by not assigning those elements classes like btn_add_event, but give them two classes: btn_add and event, or even resort to giving them id's. My solution is based on your description of your current html.
Here is what I think is a nice flexible and performant function. It assumes you can contain your links and html blocks in a parent, but otherwise it uses closures to precalculate the elements involved, so a click is super-fast.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" ></script>
<script type="text/javascript">
// Enables show/hide functionality on click.
// The elements within 'container' matching the selector 'blocks' are hidden
// When elements within 'container' matching the selector 'clicker' are clicked
// their attribute with the name 'clickerAttr' is appended to the selector
// 'subject' to identify a target, usually one of the 'blocks'. All blocks
// except the target are hidden. The target is shown.
//
// Change clickerAttr from 'linkTarget' to 'id' if you want XHTML compliance
//
// container: grouping of related elements for which to enable this functionality
// clicker: selector to element type that when clicked triggers the show/hide functionality
// clickerAttr: name of the DOM attribute that will be used to adapt the 'subject' selector
// blocks: selector to the html blocks that will be shown or hidden when the clicker is clicked
// subject: root of the selector to be used to identify the one html block to be shown
//
function initToggle(container,clicker,clickerAttr,blocks,subject) {
$(container).each(
function(idx,instance) {
var containerElement = $(instance);
var containedBlocks = containerElement.find(blocks);
containerElement.find(clicker).each(function(idxC, instanceClicker) {
var tgtE = containerElement.find(subject+instanceClicker.getAttribute(clickerAttr));
var clickerBlocks = containedBlocks.not(tgtE);
$(instanceClicker).click(function(event) {
clickerBlocks.hide();
tgtE.toggle();
});
});
// initially cleared
containedBlocks.hide();
}
);
}
$(function() {
initToggle('.toggle','a.link','linkTarget','div.block','div.');
});
</script>
</head>
<body>
Example HTML block toggle:
<div class="toggle">
a <br />
b <br />
c <br />
<div class="A block"> A </div>
<div class="B block"> B </div>
<div class="C block"> C </div>
</div> <!-- toggle -->
This next one is not enabled, to show scoping.
<div class="toggle2">
a <br />
<div class="A block">A</div>
</div> <!-- toggle2 -->
This next one is enabled, to show use in multiple positions on a page, such as in a portlet library.
<div class="toggle">
a <br />
<div class="A block">A</div>
</div> <!-- toggle (2) -->
</body>
</html>

Categories