How to rewrite text between links using Javascript [duplicate] - javascript

This question already has answers here:
How to change content of div on hover using JQuery/Javascript
(6 answers)
Closed 3 years ago.
I have a link inside a div. Inside the link (between the ), I have text displayed. I want to change that text when the cursor hovers over the link.
***One thing I forgot to mention is that I want the text to be temporarily changed (i.e. only when it's hovered over).
Here's my JSFiddle: https://jsfiddle.net/ZEZEME/kapt4sL6/5/
This is what my code looks like.
HTML
<div id="imgDiv"></div>
CSS
#imgDiv {
width: 200px;
height:200px;
background-color: gray;
}
JS
var title = "World War II Plane Crashes in National Parks";
var url = "https://www.nps.gov/articles/WWIIPlaneCrashes.htm"
$(imgDiv).append($('<a href="' + url + '" id=link>'+ title +'</a>'));
(I'm working with APIs, and .append is how I create the links. I need to dynamically create them to the div in JavaScript).
This is what I've tried:
$(imgDiv).append($('<a href="' + url + '" id=link>'+ title +'</a>').css('text-decoration', 'none').hover(function(e) {
console.log($(e.target).text("NEWWW"));
}));
This permanently changes the text (as opposed to only when hovered over).
$(imgDiv).append($('<a href="' + url + '" id=link>'+ title +'</a>').css('text-decoration', 'none').hover(function(e) {
function(e) {
console.log($(e.target).text("NEWWW"));
},
function(e) {
console.log($(e.target).text("OLDDD"));
}
This gives me an error. Can anyone help?

You can use mouseover to detect when the mouse moves over the link, you can then use mouseout to see when it leaves the link.
You also want to use text() as val() is for form fields.
var title = "World War II Plane Crashes in National Parks";
var url = "https://www.nps.gov/articles/WWIIPlaneCrashes.htm"
$('#imgDiv').append($('<a href="' + url + '" id=link>'+ title +'</a>'))
// Create an event to watch "a" tags
$('#imgDiv a').on('mouseover', (e) => {
$(e.target).text('I am some new text')
})
// Comment this out if you don't want it to go back on mouse out.
.on('mouseout', (e) => {
$(e.target).text(title)
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 200px;
height:200px;
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv"></div>

Related

Angular 7 popover loading

I am using fabricjs to load image and textcontents.
I have many textcontents on canvas with fabricjs.
now on click of textcontents of fabricjs I want to open Angular 7 popover may be (ngbPopover).
how to open that on click of textcontents, like we are opening dialogbox?
because I can not inject popover config anywhere in fabricjs.
I had similar functionality to do but I found another shortcut way in doing it so.
On click of the text, object read the object by using
this.canvas.on('object:selected', (e) => {this.objectSelected(e)});
Then initally makesure that the textbox/popover is hidden
On click of the object read the selected object by:
var absCoords = this.canvas.getActiveObject();
When you read the active object there are things that you will have to take care
unhide the textbox/popover
get absCoords.left and absCoords.top and set it to the textbox.
This is one of the workarounds which helped to solve it.
Actually I was trying to say something like this, And I found solution here.
const showImageTools = (e) => {
const content = '<div id="imageDialog" class="container">\n' +
' <mat-form-field class="example-full-width">\n' +
' <input value="' + pngText.texts + '" id="textInputField" style="width: 400px;\n' +
' box-shadow: 2px 4px 5px 3px #bdc3bdee;height: 50px;\n' +
' padding: 5px;\n' +
' border-radius: 5px;" matInput placeholder="Add your texts"/>\n' +
' </mat-form-field>\n' +
' </div>';
$("body").append(content);
moveImageTools();
};
this.canvas.add(pngText).renderAll();
pngText.on('mousedown', event => {
showImageTools(event);
});

Is there a way to insert the pathname of the current page into a div class parameter value?

I want to insert the name of the currently accessed webpage into a specific location in a div parameter value.
For example in the code below, I want to insert the page name (pathname) where you see current_page_pathname.
<div data-url="https://somedomain.com?source=current_page_pathname"></div>
I've looked at using var current_page_pathname=window.location.pathname;, but I don't know how to insert the var value where I want it.
If the currently accessed webpage is https://en.wikipedia.org/wiki/Sloth, I want the data-url value to be:
<div data-url="https://somedomain.com?source=/wiki/Sloth"></div>
Is this possible?
Am I going about this the wrong way? I'm open to any solution that works.
You can do it dynamically with javascript / jQuery
$('#urlholderlink').attr('href', 'https://somedomain.com?source=' + window.location.pathname);
$('#urlholder').attr('data-url', 'https://somedomain.com?source=' + window.location.pathname);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="urlholderlink">My link</a>
<div id="urlholder">My div</div>
NB : in this snippet the url is relative to embedded document.
You can do this with plain JavaScript.
Query all div having a data-url attribute containing the placholder current_page_pathname. For this use document.querySelectorAll('[data-url*="current_page_pathname"]')
Use forEach to iterate over each node. Use getAttribute('data-url') and setAttribute('data-url', newValue) to update the attribute, and use String.prototype.replace() to replace the placeholder by the current url.
const placeholder = 'current_page_pathname';
document.querySelectorAll(`[data-url*="${placeholder}"]`).forEach(node => {
const path = window.location.pathname;
const dataUrl = node.getAttribute('data-url').replace(placeholder, path);
node.setAttribute('data-url', dataUrl)
});
function show(e) {
console.log(e.getAttribute('data-url'));
}
div[data-url] {
cursor: pointer;
border: 1px solid black;
padding: 5px;
margin: 5px;
}
<div data-url="https://somedomain.com?source=current_page_pathname" onclick="show(this)">
Click me to view my data-url attribute
</div>
<div data-url="https://somedomain.com?source=current_page_pathname" onclick="show(this)">
Click me to view my data-url attribute
</div>
Using the url of the embedded page:
https://stacksnippets.net/js
the following demo illustrates how you may do so with JavaScript:
( function() {
let w = window;
let d = document;
let target_url = "https://www.example.com?source";
let curr_page_path = w.location.pathname;
// shortcut to access elements
let $ = id => d.getElementById( id );
let atag = $("urlholderlink");
let div = $("urlholder");
w.onload = function(){
atag.href = (div.dataset.url =
target_url + curr_page_path);
let message = "DIV attribute data-url: " + div.dataset.url;
message += '\n<a href="' + atag.href + '">';
div.onclick = function() {
console.log( message );
atag.className="viewable";
this.onclick=function(){
return null; //disable div click
}; // this.onclick
};// div.onclick
}; // w.onload
})();// IFFE
a {
float: right;
padding-right:80px;
width:50px;
color:#00f;
visibility:hidden;
}
a:hover {
text-decoration:overline;
}
#urlholder {
cursor:default;
margin-top:10%;
color:lime;
background:#000;
width: 100px;
height: 36px;
font: 32px Arial,Helvetica;
border: 15px outset #060;
}
#urlholder:hover {
color:cyan;
}
.viewable {
visibility:visible;
}
<a id="urlholderlink">My link</a>
<div id="urlholder" title="click for more info">My div</div>
The code takes advantage of the Window's onload event to call a handler, namely an anonymous function that accesses the A and DIV elements. It adds a data-url attribute to the DIV element and sets its value, using the HTML5 datalist API. The value of that assignment expression is in turn assigned as the value for the A element's href attribute.
The crux to setting these values simply involves concatenating target_url with curr_page_path;
The source for the immediately invoked function expression (IIFE) syntax comes from: https://stackoverflow.com/a/1843504/701302
The CSS is, of course optional -- added it for fun.

Restrict multiple image within div with JS/Jquery/CSS

On my webpage there are Gridster widgets.In these widgets initially the images are displayed from JSON(the name of image comes from JSON which I then put in src of image)
The users can also add images by clicking + button.User can also delete an image by clicking X button on the image.
The Problem I am facing
When the images coming from JSON are more or when the user manually adds more images then the images go out of widgets.
My Desired Output
Now I was trying to restrict those images in widget such that images will lay only in boundaries of div.
When there are more images the other existing images will resize and all of the images will fit in that area.
When I delete an image the other images will get bigger.In any case the entire area will be occupied by the images.
JS:
//JSON which I get from backend
var json = [{
"html": "https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png,https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png,https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png", //3 Images
"col": 1,
"row": 1,
"size_y": 2,
"size_x": 2
}
];
//Loop which runs over JSON to generate <li> elements in HTML
for (var index = 0; index < json.length; index++) {
var images = json[index].html.split(',');
var imageOutput = "";
for (var j = 0; j < images.length; j++) {
imageOutput += '<div class="imagewrap"><img src=' + images[j] + '> <input type="button" class="removediv" value="X" /></div></div>';
}
gridster.add_widget('<li class="new" ><button class="addmorebrands" style="float: left;">+</button><button class="delete-widget-button" style="float: right;">-</button>' + imageOutput + '<textarea>' + json[index].html + '</textarea></li>', json[index].size_x, json[index].size_y, json[index].col, json[index].row);
}
//Function to delete an image from widget
$(document).on('click', '.removediv', function() {
$(this).closest('div.imagewrap').siblings('textarea')
$(this).closest('div.imagewrap').remove();
});
//Function to delete a widget
$(document).on("click", ".delete-widget-button", function() {
var gridster = $(".gridster ul").gridster().data('gridster');
gridster.remove_widget($(this).parent());
});
//Function to add mode Images to widgets from Modal
var parentLI;
$(document).on("click", ".addmorebrands", function() {
parentLI = $(this).closest('li');
$('#exampleModalCenter').modal('show');
$('#exampleModalCenter img').click(function() {
$(this).addClass('preselect');
$(this).siblings().removeClass('preselect');
selectedImageSRC = $(this).attr('src');
})
});
$('#add-image').click(function() {
parentLI.append('<div class="imagewrap"><img src="' + selectedImageSRC + '"> <input type="button" class="removediv" value="X" /></div>');
parentLI.children('textarea').append(', ' + selectedImageSRC);
$('#exampleModalCenter').modal('hide');
})
HTML
<div class="gridster">
<!-- <li> from JSON are placed here images are a part of li -->
<ul>
</ul>
</div>
The Fiddle so far
I am not sure if this can achieved just with CSS or will require any JS along with that
Update 1
I have tried with a lot of different CSS but still not able to get the expected output so if someone can help me with it would be really helpful
Maybe Gridster has a built in way to arrange items inside the grid cells, in case you have not found a way yet, try this.
I added some css:
.image-wrap-container{
min-height: 70%
}
.image-wrap-container div.imagewrap{
width: 33%
}
.text-area-wrap{
bottom: 0px;
left: 0px;
margin: 0px;
padding: 0px;
width: 100%;
height: 30%;
display: inline-flex;
}
.new.gs-w{
width: 200px;
min-height: 200px
}
.addmorebrands{
position: absolute;
left:0
}
.delete-widget-button{
position: absolute;
right:0
}
and restructured a little bit your html so images fit good within the cell, I hope that does not break anything, javascript was the least modified, only to add the images according to the new html structure.
Note: I tried to make the lis' height adjust to the amount of elements it contains, but [data-sizey="2"] kept getting in my way, so before throwing some probably unnecessary hack on it, try and achieve that using the library's own options, good luck.
Also, I noticed you were using this to update your textareas:
parentLI.children('.imagenames').val(function(i, selectedImageSRC) {return selectedImageSRC + ', '});
which won't work because you are using the same name for the argument, conflicting with the original selectedImageSRC variable. In case you are still having problems in that front, I replaced it with:
parentLI.children('.imagenames').val(function(i, currentContent) {return currentContent + ',' + selectedImageSRC + ', '});
Bonus Feature
The buttons for removing an image were to big for the images and covered quite a big part, so I took the liberty:
.removediv{
visibility: hidden
}
.imagewrap:hover .removediv{
visibility: visible
}
hope it helps

How do I place one element precisely over another element?

How do I place an input element perfectly over another element?
I am close, but not there. Please see https://output.jsbin.com/yivitupaqe/1
As seen, the input is pushed down a bit for examples 1, 2, and 3. I could fix it by getting rid of the style on the elements which had the input added to it, but don't wish to do so. For the example 4, it is way off and I think I will need to have jQuery somehow detect if the original element is a replaced or non-replaced element.
PS. Please provide explanation of what causes this behavior.
function overlayInput(e) {
var margin = e.css('margin-top') + ' ' + e.css('margin-right') + ' ' + e.css('margin-bottom') + ' ' + e.css('margin-left');
var input = $('<input/>', {
type: 'file',
name: 'bla',
style: 'position:absolute;top: 0; bottom: 0; left: 0; right: 0;cursor:pointer;z-index:9999;opacity:0;filter:alpha(opacity=0);height:' + e.outerHeight(false) + 'px;width:' + e.outerWidth(false) + 'px;padding:0;margin:' + margin //Padding shouldn't matter
});
e.wrap($('<div/>', {
style: 'position:relative; display:' + e.css('display') + ';margin:0;padding:0'
}))
.parent().append(input);
console.log(e, input[0])
}
$(function() {
var e1 = $('#e1'),
e2 = $('#e2'),
e3 = $('#e3'),
e4 = $('#e4');
overlayInput(e1);
overlayInput(e2);
overlayInput(e3);
overlayInput(e4);
});
#e1,
#e2,
#e3,
#e4 {
border: 5px solid black;
margin: 10px;
padding: 5px;
background-color: yellow;
}
#e2 {
width: 300px;
}
div {
margin-top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>Example 1 (non-replaced inline element)<a id="e1" href="javascript:void(0)">Hello</a>bla bla bla</div>
<div>Example 2 (block element with width)
<p id="e2">Hello</p>bla bla bla</div>
<div>Example 3 (block element without width)
<p id="e3">Hello</p>bla bla bla</div>
<div>Example 4 (non-replaced inline element)
<img id="e4" alt="hi" src="http://icons.iconarchive.com/icons/hopstarter/sleek-xp-software/48/Yahoo-Messenger-icon.png" />bla bla bla</div>
I have taken a bit of time and recreated your jsbin code into jsfiddle, simplifying it and trying to illustrate my advice in the comments. It is a bit fiddly with the target elements being different types so you see slightly different effects, but for the main part, the target elements are covered with the input elements.
The key points are:
the 'original' target elements have the display and width styles that get added to the outer div that wraps everything, it also has the position: relative rule
after wrapping the original element e in the new div, get the outer dimensions of the div
the inner input can then have the standard absolute and 0 position styles along with the same width and height as the outer div
This gives us the results:
Example 1 - completely covers the link text, but not the top and bottom padding
Example 2 - completely covers the yellow box except for tiny border equivalent edge at the right hand side
Example 3 - completely covers the yellow box
Example 4 - completely covers the yellow box, but overlaps slightly by border equivalents when no image found
Hopefully this will be enough for you to work with and tweak further to get the exact levels of element coverage that you require, possibly handle different target element types to get exact coverage areas.
https://jsfiddle.net/sc7y67q0/1/

Using Javascript and CSS to align left to right

I have this line of javascript which creates a listing of store locations, and creates a DIV beneath the map. The items are displayed on the page top to bottom.
I would like to display the items as 3 in a row, left to right, top to bottom.
The function is this:
function createSidebarEntry(marker, name, address, city, state, zipcode, telephone, images, url) {
var div = document.createElement('div');
var html = "<p><a href='http://" + url + "'>" + name + "</a><br/>" + address + "<br/>" + city + ", " + state + " " + zipcode + "<br/>" + (formatPhone(telephone)) + "</p>";
div.innerHTML = html;
div.style.marginBottom = '5px';
return div;
}
As a side bar question, would tables be the preferred method?
I have tried to set the DIV as:
#sidebar {
text-align: left;
margin: 0px auto;
padding: 0px;
border:0;
width:665px;
font-size:10pt;
font-family:Arial;
color:#656668;
display: table-cell;
}
And unfortunately after working with margins, etc, I have seemed to run out of luck. Has anyone been able to use dynamic returned data and apply formatting with CSS in three columns? I have been googling and everything I see points me to creating three column styles within my DIV container.
try setting the parent element with a fixed width and apply float to the childs and a width of 33% for them. Don't forget to use a clear afterwards.
I would suggest creating your elements with jquery. It's alot easier and more elegant.
But the root of you issue is that you need to add a float:left; style to your div. This will put all your divs in the same row.
Oh, and try to use tables as little as possible to layout out elements on your page. Divs and CSS are the way to go.

Categories